2016-11-06 44 views
1

我有这样的代码:角2 - 所谓的订阅功能两次

import { Component } from '@angular/core'; 
import { ViewService } from './view.service'; 
import { Router, ActivatedRoute, Params } from '@angular/router'; 


@Component({ 
    selector: 'app-view', 
    templateUrl: './view.component.html', 
    styleUrls: ['./view.component.css'], 
    providers: [ViewService] 
}) 
    export class ViewComponent { 

     constructor(viewService: ViewService, private route: ActivatedRoute) { 

     this.route.params.map(params => params['id']).subscribe((id) => { 
      console.log("id: " + id); 
     }); 

     } 
    } 

我已经订阅我的代码运行参数。 事情是 - 订阅功能被称为两次 - 第一次 - id是未定义的。 第二次 - 存在id值。

这个问题的原因是什么?

+0

为什么你'this.route.params.map(使用'map' ....'? – Michael

+0

这只是映射值可以被删除。但并没有真正改变事情 – michali

+0

难道你曾经弄清楚这个问题?我遇到了同样的事情 – cgatian

回答

3

这里的问题是我的ViewComponent加载了两次。这就是为什么在构造函数被调用两次:

  1. 在我app.module.ts定义时路由。在这里:

    RouterModule.forRoot([ { path: '', component: ViewComponent }

  2. 在我app.component.html - 我加<app-view>标签。

+0

感谢张贴这个,真的很简单,到底和往常一样! –