Home  >  Article  >  Web Front-end  >  Building your first Angular app: storing and accessing data

Building your first Angular app: storing and accessing data

WBOY
WBOYOriginal
2023-08-28 19:05:12657browse

Building your first Angular app: storing and accessing data

In the first tutorial of this series, we learned how to get started creating an Angular application. After successfully completing this tutorial, you should now have your first working Angular application titled "Interesting Facts About Countries". Before creating any components that can be rendered on the screen, we will create some classes and define some functions that make these components useful.

In this tutorial, our focus will be on creating a Country class that will contain the different properties whose values ​​we want to display to the user. We will then create another file called country-data.ts. This file will contain information about all countries in our application. Our third file will be named country.service.ts. The name may sound fancy, but the file will only contain the CountryService class, which has all the functionality needed to retrieve and sort the information provided by the file country-data.ts.

Create country category

In the src/app folder of your Angular application, create a file called country.ts. Add the following code in it.

export class Country {
    name: string;
    capital: string;
    area: number;
    population: number;
    currency: string;
    gdp: number;
}

The TypeScript code above defines the Country class, which has six different properties to store information about different countries. Country name, capital and currency are stored as strings. However, its area, population and GDP are stored in numerical form. We will be importing the Country class in many places, so I added the export keyword before the class definition.

Create country array

The next step involves creating the country-data.ts file to store information for all countries as an array of Country objects. We will import the Country class in this file and then export a const named COUNTRIES which stores an array of country objects.

This is the code for country-data.ts. Just like country.ts, you must create this file in the src/app folder.

import { Country } from './country';

export const COUNTRIES: Country[] = [
  {
    name: 'Russia',
    capital: 'Moscow',
    area: 17098246,
    population: 144463451,
    currency: 'Russian Ruble',
    gdp: 1283162
  },
  {
    name: 'Canada',
    capital: 'Ottawa',
    area: 9984670,
    population: 35151728,
    currency: 'Canadian Dollar',
    gdp: 159760
  },
  {
    name: 'China',
    capital: 'Beijing',
    area: 9596961,
    population: 1403500365,
    currency: 'Renminbi (Yuan)',
    gdp: 11199145
  },
  {
    name: 'United States',
    capital: 'Washington, D.C.',
    area: 9525067,
    population: 325365189,
    currency: 'United States Dollar',
    gdp: 18569100
  },
  {
    name: 'Japan',
    capital: 'Tokyo',
    area: 377972,
    population: 12676200,
    currency: 'Yen',
    gdp: 4939384
  }
];

The first line in this file imports the Country class from the country.ts file located in the same directory. If you remove this line from the file, TypeScript will give the following error:

Cannot find name 'Country'.

Without the import statement, TypeScript will not know the meaning of the array of type Country. So please make sure you have imported the correct class and specified the location of country.ts correctly.

After importing the Country class, we continue to create an array of Country objects. We will import this country array for use in other files, so we also add the export keyword to this array. Currently, there are five different Country objects in the array. Each of these five objects provides key-value pairs listing the attribute names and their values ​​for a specific object or country.

If you try to add additional properties to an array that has not been declared in the Country class definition, you will receive the following error:

Object literal may only specify known properties, and 'president' does not exist in type 'Country'

In this example, I'm trying to store the president's name as a string and store it in a property called president. Since no such property was declared, we received the error. Sometimes, you may want to specify properties only for a specific object and not for other objects. In this case, you can mark the property as optional in the class definition. I discuss it in more detail in my tutorial covering TypeScript interfaces.

Now, just make sure that the names of all properties match the names in the class definition. Also make sure that the value of each property has the same type as declared in the class definition.

Create CountryService class

After creating the Country class and the COUNTRIES array, we can now finally write some functions to handle the country data. We need to import the Country class and the COUNTRIES array in the service file. This file needs to import the COUNTRIES array to access the data. Again, the file must import the Country class in order to understand the data within the COUNTRIES array.

我们还将从 Angular 核心导入其他依赖项,例如 Injectable ,以使我们的 CountryService 类可用于注入器注入其他组件。

一旦您的应用程序规模增大,不同的模块将需要相互通信。假设 ModuleA 需要 ModuleB 才能正常工作。在这种情况下,我们将 ModuleB 称为 ModuleA 的依赖项。

大多数情况下,只需将我们需要的模块导入到另一个文件中即可。然而,有时我们需要决定是否应该从 ModuleB 创建一个由整个应用程序使用的类实例,或者是否应该在每次使用模块时创建一个新实例。在我们的例子中,我们将在整个应用程序中注入 CountryService 类的单个实例。

这是 country.service.ts 的代码:

import { Injectable } from '@angular/core';

import { Country } from './country';
import { COUNTRIES } from './country-data';

@Injectable()
export class CountryService {

  constructor() { }

  getCountries(): Country[] {
    return COUNTRIES;
  }

  getPopulatedCountries(): Country[] {
    return COUNTRIES.sort((a, b) => b.population - a.population).slice(0, 3);
  }

  getLargestCountries(): Country[] {
    return COUNTRIES.sort((a, b) => b.area - a.area).slice(0, 3);
  }

  getGDPCountries(): Country[] {
    return COUNTRIES.sort((a, b) => b.gdp - a.gdp).slice(0, 3);
  }

  getCountry(name: string): Country {
    return COUNTRIES.find(country => country.name === name);
  }
}

@injectable 装饰器用于标识可能需要注入依赖项的服务类。然而,将 @injectable 添加到服务类是必需的编码风格,所以我们无论如何都会这样做。

之后,我们为该类编写不同的方法,这些方法采用 COUNTRIES 数组,直接返回它或使用特定条件对其进行排序,然后返回数组的一部分。

getCountries() 方法预计会返回所有 Country 对象,因此它会返回整个 COUNTRIES 数组,而不进行任何操作对其进行修改。

getPopulatedCountries() 采用 COUNTRIES 数组,并根据不同国家/地区的人口按降序对其进行排序。然后,我们使用 Array.slice() 方法从数组中返回前三个国家(索引为 0、1 和 2)。 getLargestCountries()getGDPCountries() 方法的工作方式类似。

getCountry() 方法采用名称作为参数,并返回 name 属性与提供的 name 参数具有相同值的国家/地区对象。

在 app.module.ts 中包含 CountryService

您创建的服务只是 Angular 中的一个类,直到您使用 Angular 依赖注入器注册它为止。 Angular 注入器将负责创建服务实例并将它们注入到需要该服务的不同类中。我们需要先向提供者注册一个服务,然后注入器才能创建该服务。

注册任何服务有两种常见方法:使用 @Component 提供商或使用 @NgModule 提供商。当您想要限制对特定组件及其所有嵌套组件的服务访问时,使用 @Component 提供程序是有意义的。当您希望多个组件能够访问该服务时,使用 @NgModule 提供程序是有意义的。

在我们的例子中,我们将使用 CountryService 与我们应用程序的多个组件。这意味着我们应该向 @NgModule 提供程序注册一次,而不是向每个组件的 @Component 提供程序单独注册。

目前,您的 app.module.ts 文件应如下所示:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

将导入语句添加到 app.module.ts 文件,并将服务添加到 @NgModule 提供程序数组。进行这些更改后,您的 app.module.ts 文件应如下所示:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { CountryService } from './country.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [CountryService],
  bootstrap: [AppComponent]
})
export class AppModule { }

CountryService 类现在可供我们为应用程序创建的所有组件使用。

最终想法

成功创建三个文件,分别名为 country.tscountry-data.tscountry.service.ts 的第二个教程结束这个系列。

country.ts 文件用于创建一个 Country 类,该类具有不同的属性,如名称、货币、人口、面积等。 country-data.ts 文件用于存储国家对象数组,其中包含不同国家的信息。 country.service.ts 文件包含一个服务类,该服务类具有不同的方法来访问 COUNTRIES 数组中的国家/地区数据。将所有这些方法单独编写在服务类中,使我们能够从一个中心位置在不同的应用程序组件中访问它们。

在上一节中,我们向 @NgModule 提供程序注册了我们的服务,以使其可在不同组件内使用。

The next tutorial will show you how to create three different components in your app to display country details and a list of countries.

The above is the detailed content of Building your first Angular app: storing and accessing data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Firebase get urlNext article:Firebase get url