角2 - 所谓的订阅功能两次
问题描述:
我有这样的代码:角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值。
这个问题的原因是什么?
答
这里的问题是我的ViewComponent加载了两次。这就是为什么在构造函数被调用两次:
-
在我
app.module.ts
定义时路由。在这里:RouterModule.forRoot([ { path: '', component: ViewComponent }
在我app.component.html - 我加
<app-view>
标签。
+0
感谢张贴这个,真的很简单,到底和往常一样! –
为什么你'this.route.params.map(使用'map' ....'? – Michael
这只是映射值可以被删除。但并没有真正改变事情 – michali
难道你曾经弄清楚这个问题?我遇到了同样的事情 – cgatian