search
HomeWeb Front-endJS TutorialSimple use of Angular4 study notes router
Simple use of Angular4 study notes routerMay 28, 2018 am 10:55 AM
routerSimple

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:

  1. ##imports: In the component Basic classes are used in the page.

  2. declarations: Existing custom component declarations.

  3. bootstrap: It can be understood as Android's main launch, which component is entered from when the project starts.

You need to introduce it before using the router:

import { RouterModule }  from &#39;@angular/router&#39;;

Because you need to call the forRoot method of RouterModule, RouterModule.forRoot and It is a basic class used in the project, so it needs to be written in imports.

 imports: [
  BrowserModule,
  FormsModule,
  RouterModule.forRoot()
 ],

RouterModule.forRoot accepts two parameters. The first is the route array to indicate the jump. The second parameter is ignored all year round. I don’t know if there is one. What's the use?

The route class includes two key attributes: path and component. By accessing the path, you can find the unique component.

Add a route array containing two components, the home page and the details page, in forRoot.

RouterModule.forRoot([
  {
    path: &#39;&#39;,
    component: AppComponent
  },
  {
    path: &#39;&#39;,
    component: GundamDetailComponent
  }
])

app.module.ts now looks like this:

import {
NgModule
} from '@angular/core';
import {
BrowserModule
} from '@angular/platform-browser';
import {
FormsModule
} from '@angular/forms';
import { RouterModule }  from &#39;@angular/router&#39;;
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 {}

Both paths are still empty, because there is still one key thing missing. Even if you write it in, an error will be reported:

Error: Cannot find primary outlet to load 'AppComponent'

In angular, router is used with the label router-outlet. In other words, router decides which component to display, and router-outlet decides where to display it.

Add the tag

<router-outlet></router-outlet>

# to the template in

app.component.ts ##Then 2 homepages are displayed as expected:


app.component.ts

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 &#39;@angular/core&#39;;
import { Gundam } from &#39;../../model/gundam&#39;;
import { GUNDAMS } from &#39;./../../service/data&#39;;
@Component({
  template: `
    <p *ngFor="let gundam of gundams" (click)="onSelected(gundam)">
      <span>
        {{gundam.name}}
      </span>
    </p>
  `
})
export class GundamHostComponent {
  gundam: Gundam = {
    name: &#39;海牛&#39;,
    type: &#39;NewType&#39;
  };
  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的值为”(空字符串)的表示不需要增加子路径。

修改详情页的路径:

{
  path: &#39;detail&#39;,
  component: GundamDetailComponent
}

在主页里增加跳转连接:

点击跳转(路径已改变)

现在点击主页的高达列表的item后,可以跳转到一个空白的详情页。之所以是空白,是因为详情页的值是需要由主页进行传递的。现在主页详情页分家以后,需要通过路由来进行值传递。

传值的方法有很多种,甚至可以传的值也有很多种。
目前我先用最笨的方法:将gundam类转化为一个字符串,将字符串传递到详情页面后再转化为gundam类。

在app.component.ts文件的class里添加函数:

parseGundamToString(gundam: Gundam): string {
  return gundam.name + &#39;&&#39; + gundam.type;
} // 将gundam类转化为固定格式的字符串

修改app.component.ts文件的template,访问gundam路径时转化传递转化过的gundam字符串

<p *ngFor="let gundam of gundams" routerLink="/detail/name=parseGundamToString(gundam)">
  <span>
  {{gundam.name}}
  </span>
</p>

修改详情页的path

{
  path: &#39;detail/:gundam&#39;,
  component: GundamDetailComponent
}

/:gundam 是一个占位符,又是参数说明。表示传递过来的参数属性是gundam。

这样在detail文件中,就可以从url的连接中拿到传递过来的高达字符串。

获得这个字符串的时机,应该是在在detail页面初始化的时候。Angular提供了所谓的的“钩子”(hook),用来标示component的活动周期—其实也就是是类似于Android里onStart或者onCreate一样的方法。

gundam-detail.component.ts的中添加OnInit钩子,或者说接口:

import { Component, OnInit } from &#39;@angular/core&#39;;

在class后面加implements关键词和OnInit来实现该接口:

export class GundamDetailComponent implements OnInit {
  selectedGundam: Gundam ;
  ngOnInit(): void {
  }
}

剩下的事情,就是读取连接上传来的参数就可以了。

读取连接上传递的参数还是要用到router里的几个类,所以需要在detail里导入。

import { ActivatedRoute, Params }  from &#39;@angular/router&#39;;

导入完成后,通过在构造器里注入的方式进行调用:

(有关注入,现在暂时没有说到)

constructor(
private route: ActivatedRoute){}

angular会自动创建ActivatedRoute的实例。

先在ngOnInit里输出看看params是什么

this.route.params.switchMap((params: Params) => console.log(params))

ps:switchMap是angular官方给的拿取url参数的方法,也是需要预先导入才可以使用:

import &#39;rxjs/add/operator/switchMap&#39;;

ps2: 有关箭头函数

(params: Params) => this.gundamStr = params[&#39;gundam&#39;]

是一个箭头函数,等同于

function(params){
  this.gundamStr = params[&#39;gundam&#39;]
}

其中params是switchMap的返回值,返回的即是通过路由连接传递过来的参数所在的类。

ps3: 箭头函数真的是整个ES6里最恶心的东西,之一。

控制台中 输出:

传递过来的参数,是一个gundam类格式化输出的字符串,所以还要在detail里补充一个反格式化字符串到gundam类的函数。

parseStringToGundam(str: string): Gundam {
  const temp = str.split(&#39;&&#39;);
  const tempGundam: Gundam = {
  name: temp[0],
  type: temp[1]
  };
  return tempGundam;
}

最终,获得detail的初始化是这个样子的

ngOnInit(): void {
  this.route.params // 通过注入的方式拿到route里的参数params
  .switchMap((params: Params) => this.gundamStr = params[&#39;gundam&#39;]) // 通过参数拿到gundam字符串并付给detail里的一个临时变量
  .subscribe(() => this.selectedGundam = this.parseStringToGundam(this.gundamStr)); // 通过反格式化函数解析临时变量并返回给作为显示的model
}

移动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后以便被其他类引用。

import {
NgModule
} from '@angular/core';
import { RouterModule }  from &#39;@angular/router&#39;;
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 {
}

然后既然已经有了这个类,可以导入到app.module.ts里使用使得整个文件看起来清爽一些。

import {
NgModule
} from &#39;@angular/core&#39;;
import {
BrowserModule
} from &#39;@angular/platform-browser&#39;;
import {
FormsModule
} from &#39;@angular/forms&#39;;
import {
AppComponent
} from &#39;./component/appcomponent/app.component&#39;;
import { GundamDetailComponent } from &#39;./component/detail/gundam-detail.component&#39;;
import { GundamHostComponent } from &#39;./component/host/gundam-host.component&#39;;
import { AppRoutingModule } from &#39;./app-routing.module&#39;;
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule // 调用路由
  ],
  declarations: [
    AppComponent,
    GundamDetailComponent,
    GundamHostComponent
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

当然,官方文档又进行了进一步简化。

既然forRoot是一个Route数组,那么数组也可以单独抽出来,当然进一步抽取也可以放到另一个文件里。

import {
NgModule
} from &#39;@angular/core&#39;;
import { RouterModule, Route }  from &#39;@angular/router&#39;;
import { GundamDetailComponent } from &#39;./component/detail/gundam-detail.component&#39;;
import { GundamHostComponent } from &#39;./component/host/gundam-host.component&#39;;
const routes: Route[] = [
  {
    path: &#39;&#39;,
    component: GundamHostComponent
  },
  {
    path: &#39;detail/:gundam&#39;,
    component: GundamDetailComponent
  }
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

我个人比较偷懒,就先抽取到这一步。

现在连主页面和详情页面都被分开了,项目的耦合度又进一步降低。

再接再厉,我们继续把业务逻辑给也分离出来。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

轻量级JS Cookie插件js-cookie的使用方法

vue-cli开发环境实现跨域请求的方法

详解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!

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
React Router使用指南:如何实现前端路由控制React Router使用指南:如何实现前端路由控制Sep 29, 2023 pm 05:45 PM

ReactRouter使用指南:如何实现前端路由控制随着单页应用的流行,前端路由成为了一个不可忽视的重要部分。ReactRouter作为React生态系统中最受欢迎的路由库,提供了丰富的功能和易用的API,使得前端路由的实现变得非常简单和灵活。本文将介绍ReactRouter的使用方法,并提供一些具体的代码示例。安装ReactRouter首先,我们需

如何通过PHP编写一个简单的在线预约系统如何通过PHP编写一个简单的在线预约系统Sep 26, 2023 pm 09:55 PM

如何通过PHP编写一个简单的在线预约系统随着互联网的普及和用户对便利性的追求,在线预约系统越来越受到欢迎。无论是餐厅、医院、美容院还是其他服务行业,都可以通过一个简单的在线预约系统来提高效率并为用户提供更好的服务体验。本文将介绍如何使用PHP编写一个简单的在线预约系统,并提供具体的代码示例。创建数据库和表格首先,我们需要创建一个数据库来存储预约信息。在MyS

如何使用Java编写一个简单的学生成绩报表生成器?如何使用Java编写一个简单的学生成绩报表生成器?Nov 03, 2023 pm 02:57 PM

如何使用Java编写一个简单的学生成绩报表生成器?学生成绩报表生成器是一个可以帮助老师或教育者快速生成学生成绩报告的工具。本文将介绍如何使用Java编写一个简单的学生成绩报表生成器。首先,我们需要定义学生对象和学生成绩对象。学生对象包含学生的姓名、学号等基本信息,而学生成绩对象则包含学生的科目成绩和平均成绩等信息。以下是一个简单的学生对象的定义:public

快速入门:使用Go语言函数实现简单的图书管理系统快速入门:使用Go语言函数实现简单的图书管理系统Jul 30, 2023 am 09:18 AM

快速入门:使用Go语言函数实现简单的图书管理系统引言:随着计算机科学领域的不断发展,软件应用的需求也越来越多样化。图书管理系统作为一种常见的管理工具,也成为很多图书馆、学校和企业必备的系统之一。在本文中,我们将使用Go语言函数来实现一个简单的图书管理系统。通过这个例子,读者可以学习到Go语言中函数的基本用法以及如何构建一个实用的程序。一、设计思路:我们首先来

如何通过C++编写一个简单的音乐推荐系统?如何通过C++编写一个简单的音乐推荐系统?Nov 03, 2023 pm 06:45 PM

如何通过C++编写一个简单的音乐推荐系统?引言:音乐推荐系统是现代信息技术的一个研究热点,它可以根据用户的音乐偏好和行为习惯,向用户推荐符合其口味的歌曲。本文将介绍如何使用C++编写一个简单的音乐推荐系统。一、收集用户数据首先,我们需要收集用户的音乐偏好数据。可以通过在线调查、问卷调查等方式来获得用户对不同类型音乐的喜好程度。将数据保存在一个文本文件或数据库

如何使用PHP开发简单的文件管理功能如何使用PHP开发简单的文件管理功能Sep 20, 2023 pm 01:09 PM

如何使用PHP开发简单的文件管理功能简介:文件管理功能在很多Web应用中都是必不可少的一部分。它允许用户上传、下载、删除和展示文件,为用户提供了便捷的文件管理方式。本文将介绍如何使用PHP开发一个简单的文件管理功能,并提供具体的代码示例。一、创建项目首先,我们需要创建一个基本的PHP项目。在项目目录下创建以下文件:index.php:主页面,用于显示上传表

如何使用PHP编写一个简单的网络爬虫如何使用PHP编写一个简单的网络爬虫Jun 14, 2023 am 08:21 AM

网络爬虫是一种自动化程序,能够自动访问网站并抓取其中的信息。这种技术在如今的互联网世界中越来越常见,被广泛应用于数据挖掘、搜索引擎、社交媒体分析等领域。如果你想了解如何使用PHP编写简单的网络爬虫,本文将会为你提供基本的指导和建议。首先,需要了解一些基本的概念和技术。爬取目标在编写爬虫之前,需要选择爬取的目标。这可以是一个特定的网站、一个特定的网页、或整个互

如何通过C++编写一个简单的扫雷游戏?如何通过C++编写一个简单的扫雷游戏?Nov 02, 2023 am 11:24 AM

如何通过C++编写一个简单的扫雷游戏?扫雷游戏是一款经典的益智类游戏,它要求玩家根据已知的雷区布局,在没有踩到地雷的情况下,揭示出所有的方块。在这篇文章中,我们将介绍如何使用C++编写一个简单的扫雷游戏。首先,我们需要定义一个二维数组来表示扫雷游戏的地图。数组中的每个元素可以是一个结构体,用于存储方块的状态,例如是否揭示、是否有雷等信息。另外,我们还需要定义

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.