Table of Contents
Create country category
Create country array
Create CountryService class
在 app.module.ts 中包含 CountryService
最终想法
Home Web Front-end JS Tutorial Building your first Angular app: storing and accessing data

Building your first Angular app: storing and accessing data

Aug 28, 2023 pm 07:05 PM
angular storage access data

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;
}
Copy after login

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
  }
];
Copy after login

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'.
Copy after login

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'
Copy after login

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);
  }
}
Copy after login

@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 { }
Copy after login

将导入语句添加到 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 { }
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Mar 07, 2024 pm 10:43 PM

This website reported on March 7 that Dr. Zhou Yuefeng, President of Huawei's Data Storage Product Line, recently attended the MWC2024 conference and specifically demonstrated the new generation OceanStorArctic magnetoelectric storage solution designed for warm data (WarmData) and cold data (ColdData). Zhou Yuefeng, President of Huawei's data storage product line, released a series of innovative solutions. Image source: Huawei's official press release attached to this site is as follows: The cost of this solution is 20% lower than that of magnetic tape, and its power consumption is 90% lower than that of hard disks. According to foreign technology media blocksandfiles, a Huawei spokesperson also revealed information about the magnetoelectric storage solution: Huawei's magnetoelectronic disk (MED) is a major innovation in magnetic storage media. First generation ME

Vue3+TS+Vite development skills: how to encrypt and store data Vue3+TS+Vite development skills: how to encrypt and store data Sep 10, 2023 pm 04:51 PM

Vue3+TS+Vite development tips: How to encrypt and store data. With the rapid development of Internet technology, data security and privacy protection are becoming more and more important. In the Vue3+TS+Vite development environment, how to encrypt and store data is a problem that every developer needs to face. This article will introduce some common data encryption and storage techniques to help developers improve application security and user experience. 1. Data Encryption Front-end Data Encryption Front-end encryption is an important part of protecting data security. Commonly used

How to clear cache on Windows 11: Detailed tutorial with pictures How to clear cache on Windows 11: Detailed tutorial with pictures Apr 24, 2023 pm 09:37 PM

What is cache? A cache (pronounced ka·shay) is a specialized, high-speed hardware or software component used to store frequently requested data and instructions, which in turn can be used to load websites, applications, services, and other aspects of the system faster part. Caching makes the most frequently accessed data readily available. Cache files are not the same as cache memory. Cache files refer to frequently needed files such as PNGs, icons, logos, shaders, etc., which may be required by multiple programs. These files are stored in your physical drive space and are usually hidden. Cache memory, on the other hand, is a type of memory that is faster than main memory and/or RAM. It greatly reduces data access time since it is closer to the CPU and faster compared to RAM

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

See all articles