重新获取路由参数更改的数据

时间:2018-01-03 16:34:21

标签: angular http angular-services angular-router

目前,我有:

  ngOnInit() {
    this.getPi();
  }

  getPi(): void {
    const term = this.route.snapshot.paramMap.get('category');
    console.log(term);
    this.piService.getPi(this.route.snapshot.paramMap.get('term')).subscribe(pi => {
      this.pi = pi;
    });
  }

导航到localhost:4200 / term1时,此工作正常。但是,当我导航到另一个术语(例如localhost:4200 / term2)时,ngOnInit不会被触发,因为没有其他组件被加载。

我应该如何观看更改,以便调用getPi()?

2 个答案:

答案 0 :(得分:1)

您可以通过创建订阅变量来反应性地重新获取

termSubscriber: Subscription;

并且可能想要导入

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

和术语变量

term: string;

然后订阅它

ngOnInit() { 
    this.termSubscriber= this.route.params
    .subscribe(
    (params: {Params}) => {
      this.term = params['term']);
    });
}

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

(想要像OnInit一样导入OnDestroy)

注意,如果term1是不是parmae​​ter的路线,我将其转换为

'/term/:id'

所以你可以将id部分设为可取的。

答案 1 :(得分:0)

您有两种方法:Observable + async pipemanually subscribe/unsubscribe

第一种方法(最好的IMO):

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/share';

export class FooComponent {
   pi$: Observable<any>;
   constructor(private piService: PiService){
      this.pi$ = this.route.paramMap.map(paramMap => paramMap.get('term')) /// map the route params to one element
     .switchMap(term => this.piService.getPi(term)) // change the main stream to the Http async request
     .share(); // prevent the request being done multiple times
   }
}

此外,您需要在模板中使用async管道。

第二种方法:

import {Subscription} from 'rxjs/Subscription';

export class FooComponent implements OnInit, OnDestroy {
   private termSub = Subscription.EMPTY;
   private term: any;
   ngOnInit(){
      this.termSub = this.route.paramMap.map(paramMap => paramMap.get('term')) /// map the route params to one element
      .subscribe(term => {
        this.term = term;
        this.getPi();
      });
   }

   getPi(){
     this.piService.getPi(this.term).subscribe(pi => this.pi = pi);
   }

   ngOnDestroy() {
     this.termSub.unsubscribe();
   }
}