[英]angular 2 - subscribe function called twice
我有以下代碼:
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>
標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.