Simple use of Angular4 study notes router
This article mainly introduces the simple use of Angular4 study notes router. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
router, that is, routing, is a relatively important concept in the front-end. The specific address and the corresponding page are associated and separated through the router to achieve the purpose of decoupling. Create a new detail folder in the src/app directory and create a file named gundam-detail.component.
import { Component } from '@angular/core'; import { Gundam } from '../../model/gundam'; @Component({ template: ` <p *ngIf="selectedGundam"> <span>{{selectedGundam.name}}</span> <span>{{selectedGundam.type}}</span> </p> ` }) export class GundamDetailComponent { selectedGundam: Gundam; }
ps: Regarding naming, basically the naming method of xxx “-” “business type” “component type” is used, at least that’s how it is in the official documents recommended. Of course, you can also name the component Zhutou San, but standard naming can increase the readability of the component. Even if you don't mind naming random maintainers, no one can be sure that they won't refactor the same piece of code again in a long time. Therefore, you still have to be kind. It’s okay if you don’t write comments. It’s better to be more standardized in naming.
ps2: Regarding the subcontracting method, some people like to put the views together and the controllers together, and then further subdivide them according to the logic; some people do it the other way around, dividing the logic first and then the views and controllers. There seems to be no unified conclusion on this. I personally prefer the latter method, so this project adopts the latter method.
There is nothing in the file at present, it is just a simple move of the temple in app.component.ts.
First clarify the requirements, and then start writing the router.
Requirements: Click on any item in the gundam list page to jump to the gundam details page.
As an angular component, if you want to use router in the page, you must first declare it in app.module.ts.
ps: The previous business has nothing to do with app.module.ts, but this does not mean that it is not important. app.module.ts is equivalent to the mainifist file of Android, which coordinates and manages the entire project.
Open app.module.ts:
- ##imports: In the component Basic classes are used in the page.
- declarations: Existing custom component declarations.
- bootstrap: It can be understood as Android's main launch, which component is entered from when the project starts.
import { RouterModule } from '@angular/router';
imports: [ BrowserModule, FormsModule, RouterModule.forRoot() ],
RouterModule.forRoot([ { path: '', component: AppComponent }, { path: '', component: GundamDetailComponent } ])
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { AppComponent } from './component/appcomponent/app.component'; import { GundamDetailComponent } from './component/detail/gundam-detail.component'; @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule.forRoot([ { path: '', component: AppComponent }, { path: '', component: GundamDetailComponent } ]) ], declarations: [ AppComponent, GundamDetailComponent ], bootstrap: [AppComponent], }) export class AppModule {}
<router-outlet></router-outlet>
app.component.ts ##Then 2 homepages are displayed as expected:
is a component and a page, angular First, enter app.component.ts from bootstrap to render the interface (that is, the part above router-outlet). I went to find the router again and found that the corresponding router also had components, so I loaded it again. So in order to display it normally, the homepage must also be extracted separately. All components are loaded through
app.component.ts. As the outermost container of the entire demo, app.component.ts can perform some common operations (typical: back action). Create a new host package under src and a new gundam-host.component.ts file.
Basically, you can move the entire app, delete the out tag, and delete the selector (not used for the time being).import { Component } from '@angular/core'; import { Gundam } from '../../model/gundam'; import { GUNDAMS } from './../../service/data'; @Component({ template: ` <p *ngFor="let gundam of gundams" (click)="onSelected(gundam)"> <span> {{gundam.name}} </span> </p> ` }) export class GundamHostComponent { gundam: Gundam = { name: '海牛', type: 'NewType' }; gundams = GUNDAMS; selectedGundam: Gundam; // 定义一个selectedGudam作为展示详情的变量 onSelected (gundam: Gundam): void { this.selectedGundam = gundam; // 通过参数赋值 } }
app.component.ts Only keep the tags and remove everything else.
Modify the
app.module.ts file, import gundam-host.component.ts and add GundamHostComponent to the component declaration declarations. 修改route里的path所指向的component,默认进入后显示主页组件: before after path的值为”(空字符串)的表示不需要增加子路径。 修改详情页的路径: 在主页里增加跳转连接: 点击跳转(路径已改变) 现在点击主页的高达列表的item后,可以跳转到一个空白的详情页。之所以是空白,是因为详情页的值是需要由主页进行传递的。现在主页详情页分家以后,需要通过路由来进行值传递。 传值的方法有很多种,甚至可以传的值也有很多种。 在app.component.ts文件的class里添加函数: 修改app.component.ts文件的template,访问gundam路径时转化传递转化过的gundam字符串 修改详情页的path /:gundam 是一个占位符,又是参数说明。表示传递过来的参数属性是gundam。 这样在detail文件中,就可以从url的连接中拿到传递过来的高达字符串。 获得这个字符串的时机,应该是在在detail页面初始化的时候。Angular提供了所谓的的“钩子”(hook),用来标示component的活动周期—其实也就是是类似于Android里onStart或者onCreate一样的方法。 在gundam-detail.component.ts的中添加OnInit钩子,或者说接口: 在class后面加implements关键词和OnInit来实现该接口: 剩下的事情,就是读取连接上传来的参数就可以了。 读取连接上传递的参数还是要用到router里的几个类,所以需要在detail里导入。 导入完成后,通过在构造器里注入的方式进行调用: (有关注入,现在暂时没有说到) angular会自动创建ActivatedRoute的实例。 先在ngOnInit里输出看看params是什么 ps:switchMap是angular官方给的拿取url参数的方法,也是需要预先导入才可以使用: ps2: 有关箭头函数 是一个箭头函数,等同于 其中params是switchMap的返回值,返回的即是通过路由连接传递过来的参数所在的类。 ps3: 箭头函数真的是整个ES6里最恶心的东西,之一。 控制台中 输出: 传递过来的参数,是一个gundam类格式化输出的字符串,所以还要在detail里补充一个反格式化字符串到gundam类的函数。 最终,获得detail的初始化是这个样子的 移动web页面间传值确实没有什么太好的方法,angular和react都是如此。以前我们的做法是短的参数直接挂连接传走,长的大的或者object的参数就先保存本地,然后第二个页面再从本地读取。 但是像android那样扔一个intent里直接就过去了的方式,确实没有。 回首页: 点击一个列表: 包结构: 总的来说,业务被分开了,结构干净多了。虽然现在还体现不出来,但是写到后来就觉得心花怒放,磨刀不误砍柴工功啊。 作为router,也可以分离的。 目前我的项目里只有2个页面,如果多起来-比如20来个,那么app.module.ts又会变的乱七八糟。 所以要把router也给扔出去。 新建一个文件app-routing.module.ts,然后把footRoot平移过来(带上引用)。 在app-routing.module.ts文件里,也需要ngModul。个人理解ngModul就相当于一个基类指示器,导出class后以便被其他类引用。 然后既然已经有了这个类,可以导入到app.module.ts里使用使得整个文件看起来清爽一些。 当然,官方文档又进行了进一步简化。 既然forRoot是一个Route数组,那么数组也可以单独抽出来,当然进一步抽取也可以放到另一个文件里。 我个人比较偷懒,就先抽取到这一步。 现在连主页面和详情页面都被分开了,项目的耦合度又进一步降低。 再接再厉,我们继续把业务逻辑给也分离出来。 上面是我整理给大家的,希望今后会对大家有帮助。 相关文章: 详解Vue-cli webpack移动端自动化构建rem问题 The above is the detailed content of Simple use of Angular4 study notes router. For more information, please follow other related articles on the PHP Chinese website!
{
path: 'detail',
component: GundamDetailComponent
}
目前我先用最笨的方法:将gundam类转化为一个字符串,将字符串传递到详情页面后再转化为gundam类。parseGundamToString(gundam: Gundam): string {
return gundam.name + '&' + gundam.type;
} // 将gundam类转化为固定格式的字符串
<p *ngFor="let gundam of gundams" routerLink="/detail/name=parseGundamToString(gundam)">
<span>
{{gundam.name}}
</span>
</p>
{
path: 'detail/:gundam',
component: GundamDetailComponent
}
import { Component, OnInit } from '@angular/core';
export class GundamDetailComponent implements OnInit {
selectedGundam: Gundam ;
ngOnInit(): void {
}
}
import { ActivatedRoute, Params } from '@angular/router';
constructor(
private route: ActivatedRoute){}
this.route.params.switchMap((params: Params) => console.log(params))
import 'rxjs/add/operator/switchMap';
(params: Params) => this.gundamStr = params['gundam']
function(params){
this.gundamStr = params['gundam']
}
parseStringToGundam(str: string): Gundam {
const temp = str.split('&');
const tempGundam: Gundam = {
name: temp[0],
type: temp[1]
};
return tempGundam;
}
ngOnInit(): void {
this.route.params // 通过注入的方式拿到route里的参数params
.switchMap((params: Params) => this.gundamStr = params['gundam']) // 通过参数拿到gundam字符串并付给detail里的一个临时变量
.subscribe(() => this.selectedGundam = this.parseStringToGundam(this.gundamStr)); // 通过反格式化函数解析临时变量并返回给作为显示的model
}
import {
NgModule
} from '@angular/core';
import { RouterModule } from '@angular/router';
import { GundamDetailComponent } from './component/detail/gundam-detail.component';
import { GundamHostComponent } from './component/host/gundam-host.component';
@NgModule({
imports: [
RouterModule.forRoot([
{
path: '',
component: GundamHostComponent
},
{
path: 'detail/:id',
component: GundamDetailComponent
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
import {
NgModule
} from '@angular/core';
import {
BrowserModule
} from '@angular/platform-browser';
import {
FormsModule
} from '@angular/forms';
import {
AppComponent
} from './component/appcomponent/app.component';
import { GundamDetailComponent } from './component/detail/gundam-detail.component';
import { GundamHostComponent } from './component/host/gundam-host.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule // 调用路由
],
declarations: [
AppComponent,
GundamDetailComponent,
GundamHostComponent
],
bootstrap: [AppComponent],
})
export class AppModule {}
import {
NgModule
} from '@angular/core';
import { RouterModule, Route } from '@angular/router';
import { GundamDetailComponent } from './component/detail/gundam-detail.component';
import { GundamHostComponent } from './component/host/gundam-host.component';
const routes: Route[] = [
{
path: '',
component: GundamHostComponent
},
{
path: 'detail/:gundam',
component: GundamDetailComponent
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule {
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to write a simple online reservation system through PHP. With the popularity of the Internet and users' pursuit of convenience, online reservation systems are becoming more and more popular. Whether it is a restaurant, hospital, beauty salon or other service industry, a simple online reservation system can improve efficiency and provide users with a better service experience. This article will introduce how to use PHP to write a simple online reservation system and provide specific code examples. Create database and tables First, we need to create a database to store reservation information. In MyS

How to write a simple student performance report generator using Java? Student Performance Report Generator is a tool that helps teachers or educators quickly generate student performance reports. This article will introduce how to use Java to write a simple student performance report generator. First, we need to define the student object and student grade object. The student object contains basic information such as the student's name and student number, while the student score object contains information such as the student's subject scores and average grade. The following is the definition of a simple student object: public

Quick Start: Implementing a Simple Library Management System Using Go Language Functions Introduction: With the continuous development of the field of computer science, the needs of software applications are becoming more and more diverse. As a common management tool, the library management system has also become one of the necessary systems for many libraries, schools and enterprises. In this article, we will use Go language functions to implement a simple library management system. Through this example, readers can learn the basic usage of functions in Go language and how to build a practical program. 1. Design ideas: Let’s first

Introduction to how to use PHP to develop simple file management functions: File management functions are an essential part of many web applications. It allows users to upload, download, delete and display files, providing users with a convenient way to manage files. This article will introduce how to use PHP to develop a simple file management function and provide specific code examples. 1. Create a project First, we need to create a basic PHP project. Create the following file in the project directory: index.php: main page, used to display the upload table

How to write a simple music recommendation system in C++? Introduction: Music recommendation system is a research hotspot in modern information technology. It can recommend songs to users based on their music preferences and behavioral habits. This article will introduce how to use C++ to write a simple music recommendation system. 1. Collect user data First, we need to collect user music preference data. Users' preferences for different types of music can be obtained through online surveys, questionnaires, etc. Save data in a text file or database

A simple calculator is a calculator that performs some basic operations, such as "+", "-", "*", "/". The calculator can perform basic operations quickly. We will use the switch statement to make a calculator. Example Operator−‘+’=>34+324=358Operator−‘-’=>3874-324=3550Operator−‘*’=>76*24=1824O
