Bermula dengan Sudut: Menambah Laluan pada Aplikasi Pertama Anda

WBOY
Lepaskan: 2023-09-04 15:33:08
asal
1443 orang telah melayarinya

Angular 入门:向您的第一个应用程序添加路由

Sebelum meneruskan tutorial ini, adalah idea yang baik untuk merumuskan semua yang telah kami lakukan setakat ini untuk mengelakkan sebarang kekeliruan dan kesilapan. Jika anda terlepas sebarang langkah dalam tiga tutorial terakhir, adalah idea yang baik untuk kembali dan membuat perubahan yang diperlukan.

Dalam tutorial kedua, kami mencipta tiga fail berbeza bernama country.ts, country-data .ts dan country.service. ts. Fail country.ts digunakan untuk menyimpan definisi kelas Country supaya kami boleh mengimportnya ke dalam fail yang berbeza. Fail country-data.ts menyimpan tatasusunan bernama COUNTRIES. country.tscountry-data.tscountry.service。 tscountry.ts 文件用于存储 Country 类定义,以便我们可以将其导入到不同的文件中。 country-data.ts 文件用于存储名为 COUNTRIES 的数组。

该数组存储我们想要在应用程序中显示的所有国家/地区对象。 country.service.ts 文件用于定义 CountryService 类,其中包含我们将用于在一个地方访问不同国家/地区信息的所有方法。 CountryService 类的方法用于根据人口和面积等条件获取排名靠前的国家/地区,或查找有关给定名称的国家/地区的信息。

在第三个教程中,我们为我们的应用程序创建了 HomeComponent。这是在名为 home.component.tshome.component.htmlhome.component.css 的三个不同文件的帮助下完成的。 home.component.ts 文件包含 HomeComponent 类的定义,该类具有不同的方法和属性来访问和存储有关所有国家/地区的信息。

HomeComponent 类中的方法依赖于 country.service.ts 中定义的方法来获取所有数据。 home.component.html 文件用于存储模板,该模板将在显示通过 home.component.ts 文件中定义的方法访问的所有数据时使用。 home.component.css 文件用于提供不同的样式规则,这些规则将控制模板内不同元素的外观。

在第四个教程中,我们为我们的应用程序创建了另外两个组件。对于 AllCountries 组件,我们创建了名为 all-countries.component.tsall-countries.component.htmlall-countries.component.css。对于 CountryDetail 组件,我们创建了名为 country-detail.component.tscountry-detail.component.htmlcountry-detail.component.css。就像 HomeComponent 一样,.ts 文件包含我们组件的逻辑,.html 文件包含模板,而 .css 文件包含应用于模板文件中的元素的不同规则。

在本教程中,我们将在我们的应用程序中实现路由。这样,用户将能够轻松地从一个组件导航到另一个组件。

修改应用程序外壳

现在,我们只需要对应用程序 shell 进行更改即可让我们的应用程序开始工作。 app.component.ts 文件将与第一个教程中的完全相同。

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Fun Facts About Countries';
}
Salin selepas log masuk

但是,我们将对 app.component.html 文件进行更改。 HTML 文件现在应包含以下代码:

<h1>{{title}}</h1>
<nav>
  <a routerLink="/home">Go Back to Homepage</a>
  <a routerLink="/all-countries">List of all Countries</a>
</nav>
<router-outlet></router-outlet>
Salin selepas log masuk

之前,我们只显示应用程序的标题。现在,我们还向模板添加了导航。 routerLink 指令用于提供指向应用程序不同部分或页面的链接。 Angular 在 routerLink 指令的帮助下确定需要显示的组件。这些组件的渲染位置是使用 routerOutlets 控制的。这些组件在 router-outlet 标记之后呈现。

创建模板文件后,我们将以下 CSS 添加到 app.component.css 来设置导航链接和标题的样式:

nav {
  margin: 0px;
  text-align: center;
}

h1 {
  font-family: 'Lato';
  color: #999;
  text-align: center;
}

h2 {
  font-size: 2em;
  margin-top: 0;
  padding-top: 0;
}

nav a {
  padding: 10px;
  text-decoration: none;
  margin: 10px 0px;
  display: inline-block;
  background-color: black;
  color: white;
  border-radius: 5px;
  font-family: 'Lato';
}

nav a:hover {
  background-color: gray;
}

nav a.active {
  color: #039be5;
}
Salin selepas log masuk

现在我们将告诉 Angular 需要为特定路线或路径渲染哪些组件。在 src/app 目录中创建一个名为 app-routing.module.ts

Susun atur ini menyimpan semua objek negara yang ingin kami paparkan dalam aplikasi. Fail country.service.ts digunakan untuk mentakrifkan kelas CountryService yang akan kami gunakan untuk mengakses negara yang berbeza di satu tempat Semua kaedah maklumat. Kaedah kelas CountryService digunakan untuk mendapatkan negara teratas berdasarkan kriteria seperti populasi dan kawasan, atau untuk mencari maklumat tentang negara dengan nama tertentu. #🎜🎜# #🎜🎜#Dalam tutorial ketiga, kami mencipta HomeComponent untuk aplikasi kami. Ini dilakukan dalam fail bernama home.component.ts, home.component.html dan home Ini dilakukan dengan bantuan tiga fail berbeza .component.css. Fail home.component.ts mengandungi takrif kelas HomeComponent, yang mempunyai kaedah dan sifat yang berbeza untuk mengakses dan menyimpan maklumat tentang semua maklumat Negara. #🎜🎜# #🎜🎜#Kaedah dalam kelas HomeComponent bergantung pada kaedah yang ditakrifkan dalam country.service.ts untuk mendapatkan semua data . Fail home.component.html digunakan untuk menyimpan templat yang akan dipaparkan melalui kaedah home.component.ts untuk mengakses semua data. Fail home.component.css digunakan untuk menyediakan peraturan gaya berbeza yang akan mengawal penampilan elemen berbeza dalam templat. #🎜🎜# #🎜🎜#Dalam tutorial keempat, kami mencipta dua lagi komponen untuk aplikasi kami. Untuk komponen AllCountries, kami mencipta fail bernama all-countries.component.ts, semua Fail "sebaris" untuk -countries.component.html dan all-countries.component.css. Untuk komponen CountryDetail, kami mencipta fail bernama country-detail.component.ts, country Fail "inline" untuk -detail.component.html dan country-detail.component.css. Sama seperti HomeComponent, fail .ts mengandungi logik untuk komponen kami, .html< Fail / The code> mengandungi templat, manakala fail <code class="inline">.css mengandungi peraturan berbeza yang digunakan pada elemen dalam fail templat. #🎜🎜# #🎜🎜#Dalam tutorial ini, kami akan melaksanakan penghalaan dalam aplikasi kami. Dengan cara ini, pengguna akan dapat menavigasi dari satu komponen ke komponen yang lain dengan mudah. #🎜🎜#

Ubah suai shell aplikasi

#🎜🎜#Kini kami hanya perlu membuat perubahan pada shell aplikasi untuk membolehkan aplikasi kami berfungsi. Fail app.component.ts akan sama seperti dalam tutorial pertama. #🎜🎜#
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { AllCountriesComponent } from './all-countries/all-countries.component';
import { CountryDetailComponent } from './country-detail/country-detail.component';

const routes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'detail/:name', component: CountryDetailComponent },
    { path: 'all-countries', component: AllCountriesComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})

export class AppRoutingModule { }
Salin selepas log masuk
Salin selepas log masuk
#🎜🎜#Walau bagaimanapun, kami akan membuat perubahan pada fail app.component.html. Fail HTML kini sepatutnya mengandungi kod berikut: #🎜🎜#
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { CountryService } from './country.service';
import { HomeComponent } from './home/home.component';
import { AllCountriesComponent } from './all-countries/all-countries.component';
import { CountryDetailComponent } from './country-detail/country-detail.component';

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

export class AppModule { }
Salin selepas log masuk
Salin selepas log masuk
#🎜🎜#Sebelum ini, kami hanya memaparkan tajuk aplikasi. Kini, kami juga telah menambahkan navigasi pada templat. Arahan routerLink digunakan untuk menyediakan pautan ke bahagian atau halaman aplikasi yang berlainan. Angular menentukan komponen mana yang perlu dipaparkan dengan bantuan arahan routerLink. Kedudukan pemaparan komponen ini dikawal menggunakan routerOutlets. Komponen ini dipaparkan selepas teg router-outlet. #🎜🎜# #🎜🎜#Selepas mencipta fail templat, kami menambah CSS berikut pada app.component.css untuk menggayakan pautan navigasi dan tajuk: #🎜🎜#
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { CountryService } from './country.service';
import { HomeComponent } from './home/home.component';
import { AllCountriesComponent } from './all-countries/all-countries.component';
import { CountryDetailComponent } from './country-detail/country-detail.component';

import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AllCountriesComponent,
    CountryDetailComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [CountryService],
  bootstrap: [AppComponent]
})

export class AppModule { }
Salin selepas log masuk
Salin selepas log masuk
#🎜🎜#Sekarang kami akan memberitahu Angular komponen yang perlu diberikan untuk laluan atau laluan tertentu. Buat fail bernama app-routing.module.ts dalam direktori src/app dan letakkan kod berikut Antaranya: # 🎜🎜#
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { AllCountriesComponent } from './all-countries/all-countries.component';
import { CountryDetailComponent } from './country-detail/country-detail.component';

const routes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'detail/:name', component: CountryDetailComponent },
    { path: 'all-countries', component: AllCountriesComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})

export class AppRoutingModule { }
Salin selepas log masuk
Salin selepas log masuk

我们首先导入所有必要的依赖项,包括我们想要为不同路由渲染的组件。之后,我们指定不同的路径以及当用户访问这些路径时应呈现的组件。您还可以重定向路径,就像我们对此国家/地区信息应用程序所做的那样。每当用户访问 http://localhost:4200/ 时,他们都会被重定向到 http://localhost:4200/home。请记住,指定重定向路由需要您为 pathMatch 属性指定一个值,以告诉路由器如何将 URL 与任何路由的路径相匹配。

如果用户访问 http://localhost:4200/all-countries,我们将在 router-outlet 标记之后呈现 AllCountriesComponent >app.component.html 文件显示所有国家/地区的列表。

我们在 AllCountriesComponent 以及 HomeComponent 的模板中使用了 routerLink 指令来提供用户可以点击阅读的链接更多关于任何国家的信息。在这些模板中呈现的每个国家/地区的 routerLink 值遵循以下格式:routerLink="/detail/{{country.name}}"。用于渲染 path 属性的值 CountryDetailComponent 已指定为 detail/:name,保留 routerLink 记住指令。该路径中的 :name 部分用于标识国家/地区的名称。

更新 app.module.ts 文件

为了拥有一个功能齐全的 Angular 应用程序,我们需要做的最后一件事是更新 app.module.ts 文件。如果您在文本编辑器中打开此文件,您会注意到我们使用 Angular CLI 生成的所有三个组件都已导入到该文件中。在我们进行任何更改之前,您的 app.module.ts 文件应包含以下代码:

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

import { AppComponent } from './app.component';
import { CountryService } from './country.service';
import { HomeComponent } from './home/home.component';
import { AllCountriesComponent } from './all-countries/all-countries.component';
import { CountryDetailComponent } from './country-detail/country-detail.component';

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

export class AppModule { }
Salin selepas log masuk
Salin selepas log masuk

我们只需对 app.module.ts 文件进行两处更改。首先,我们必须从我们在上一节中创建的 app-routing.module.ts 文件中导入 AppRoutingModule 类。其次,将该类添加到 @NgModule.providers 数组中。进行这些更改后,您的 app.module.ts 文件应如下所示。

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

import { AppComponent } from './app.component';
import { CountryService } from './country.service';
import { HomeComponent } from './home/home.component';
import { AllCountriesComponent } from './all-countries/all-countries.component';
import { CountryDetailComponent } from './country-detail/country-detail.component';

import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AllCountriesComponent,
    CountryDetailComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [CountryService],
  bootstrap: [AppComponent]
})

export class AppModule { }
Salin selepas log masuk
Salin selepas log masuk

如果您移动到项目目录并在控制台中键入以下命令,您的应用程序将加载并呈现 HomeComponent

ng serve --open
Salin selepas log masuk

您可以单击各个国家/地区块或导航链接来加载不同的组件。

最终想法

在本系列中,我想教以前从未使用过 Angular 的读者如何创建基本的 Angular 应用。仅在我们完成上一个教程后,该应用程序才开始正常运行。这是故意的,因为我想避免在相同的文件之间来回移动,进行需要在后续教程中覆盖的更改。这对于初学者来说可能会非常困惑,因此我们只是一次性对文件进行了所有更改。

为了练习,您可以尝试创建更多组件,以不同的格式显示有关国家/地区的信息。

此外,如果还不清楚的话,JavaScript 已经成为事实上的网络语言之一。正如 Angular 在本教程中所演示的那样,它并非没有学习曲线,并且有大量的框架和库可以让您忙碌起来。如果您正在寻找其他资源来学习或在工作中使用,请查看我们在 Envato Market 中提供的资源。

如果您对本教程或本系列的任何其他教程有任何疑问,请随时发表评论。

Atas ialah kandungan terperinci Bermula dengan Sudut: Menambah Laluan pada Aplikasi Pertama Anda. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!