Angularv4.初体验


1203 浏览 5 years, 2 months

8 模块动态路由 Dynamic Routing of Component

版权声明: 转载请注明出处 http://www.codingsoho.com/

08 Dynamic Routing of Component

在上面path:"videos/:slug"中,slug是一个参数,接下来会讲讲怎么去处理这个参数

在video-detail.component.ts导入模块ActivatedRote

import { ActivatedRoute } from '@angular/router';

同时在OnInt里添加注册函数

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      console.log(params)
    }) 
  }

这个函数跟下面的功能相似,typescript做了优化

  ngOnInit() {
    this.route.params.subscribe(function(params){
      console.log(params)
    })    
  }

程序销毁时,我们希望取消这个注册,可以通过ngOnDestroy来实现

更新video-detail.component.ts如下

import { Component, OnInit, OnDestroy } from '@angular/core';
export class VideoDetailComponent implements OnInit, OnDestroy {
  private routeSub:any;
  slug:string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.routeSub = this.route.params.subscribe(params => {
      console.log(params);
      this.slug = params['slug']
    }) 
  }

  ngOnDestroy() {
    this.routeSub.unsubscribe()
  }
}

首先将注册对象保持到this.routeSub,然后在销毁时将其unsubscribe

this.slug = params['slug']将slug参数读入到slug变量,如果有多个变量也可以一起读入。然后可以在模板里渲染这个变量,例如

在video-detail.component.html

<p>
  video-detail works! {{slug}}!!!
</p>