search
HomeWeb Front-endJS TutorialBuilding your first Angular app: storing and accessing 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;
}

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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)