简体   繁体   English

Angular 2中的路径参数

[英]Route Parameters in Angular 2

I am working on sample Angular 2 application , and below is the code of one of my components. 我正在研究示例Angular 2应用程序,下面是我的组件之一的代码。

export class ProductComponent implements OnInit {

  product:Product;

  constructor(private appService: AppService , private router:Router ,private route:ActivatedRoute) {}

 ngOnInit() 
 {

    let id:string;
    let pid:string;

    this.route.params.subscribe( (params) => {
    id = params['id'];
    pid = params['pid'];       
    this.appService.GetProduct(id,pid).subscribe( data => {
        this.product = data;
    });
})

} }

In this partcular component , my intention is to read both the route parameters(id , pid) and then make a call to service method. 在这个特殊的组件中,我的意图是读取两个路由参数(id,pid),然后调用service方法。 But because there are 2 route parameters to read , the service method is called twice. 但是由于有两个要读取的路由参数,因此服务方法被调用了两次。

Any idea what needs to be modified so that service method is called once ? 任何想法都需要修改,以便一次调用服务方法吗?

You can use switchMap: 您可以使用switchMap:

this.route.params
.switchMap(({id, pid}) => appService.GetProduct(id,pid))
.subscribe(data => this.product = data);

Below text from this link solved my issue. 下面来自链接的文字解决了我的问题。

Right now, if an error happens during detecting changes of content/view children of a component, ngOnInit will be called twice (seen in DynamicChangeDetector). 现在,如果在检测组件的内容/视图子项的更改期间发生错误,则ngOnInit将被调用两次(在DynamicChangeDetector中可见)。 This can lead to follow up errors that hide the original error. 这可能导致跟踪错误,从而隐藏原始错误。

In my case also , there was some other error in my component , which resulted in ngOnInit() executing twice.. hope this will be helpfull to others. 同样在我的情况下,我的组件中还有其他错误,导致ngOnInit()执行了两次。希望对其他人有帮助。 I had spent 2 hrs on this issue :( 我在这个问题上花了2个小时:(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM