Home > Web Front-end > JS Tutorial > body text

Getting Started with Angular: Adding Routes to Your First Application

WBOY
Release: 2023-09-04 15:33:08
Original
1430 people have browsed it

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

Before continuing with this tutorial, it’s a good idea to summarize everything we’ve done so far to avoid any confusion and mistakes. If you missed any steps in the last three tutorials, it's a good idea to go back and make the necessary changes.

In the second tutorial, we created three different files named country.ts, country-data.ts and country.service . ts. The country.ts file is used to store the Country class definition so that we can import it into different files. The country-data.ts file is used to store an array named COUNTRIES.

This array stores all the country objects we want to display in the application. The country.service.ts file is used to define the CountryService class which contains all the methods we will use to access different country information in one place. Methods of the CountryService class are used to get the top countries based on criteria such as population and area, or to find information about a country with a given name.

In the third tutorial, we created the HomeComponent for our application. This is done with the help of three different files named home.component.ts, home.component.html and home.component.css . The home.component.ts file contains the definition of the HomeComponent class, which has different methods and properties to access and store information about all countries.

The methods in the

HomeComponent class rely on the methods defined in country.service.ts to get all the data. The home.component.html file is used to store the template that will be used when displaying all data accessed through the methods defined in the home.component.ts file. The home.component.css file is used to provide different style rules that will control the appearance of different elements within the template.

In this fourth tutorial, we create two more components for our application. For the AllCountries components, we created components named all-countries.component.ts, all-countries.component.html and all-countries. component.css. For the CountryDetail components, we created components named country-detail.component.ts, country-detail.component.html and country-detail. component.css. Just like HomeComponent, the .ts file contains the logic for our component, the .html file contains the templates, and the .css file contains the application Different rules for elements in template files.

In this tutorial, we will implement routing in our application. This way, users will be able to navigate from one component to another easily.

Modify application shell

Now we just need to make changes to the application shell to get our application working. The app.component.ts file will be exactly the same as in the first tutorial.

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

However, we will make changes to the app.component.html file. The HTML file should now contain the following code:

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

Previously, we only displayed the title of the application. Now, we've also added navigation to the template. The routerLink directive is used to provide links to different parts or pages of the application. Angular determines which component needs to be displayed with the help of the routerLink directive. The rendering position of these components is controlled using routerOutlets. These components are rendered after the router-outlet tag.

After creating the template file, we add the following CSS to app.component.css to style the navigation links and headers:

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

Now we will tell Angular which components need to be rendered for a specific route or path. Create a file called app-routing.module.ts in the src/app directory and put the following code into it:

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

我们首先导入所有必要的依赖项,包括我们想要为不同路由渲染的组件。之后,我们指定不同的路径以及当用户访问这些路径时应呈现的组件。您还可以重定向路径,就像我们对此国家/地区信息应用程序所做的那样。每当用户访问 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 { }
Copy after login

我们只需对 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 { }
Copy after login

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

ng serve --open
Copy after login

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

最终想法

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

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

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

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

The above is the detailed content of Getting Started with Angular: Adding Routes to Your First Application. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!