我在ActivationEnd路由器服务内访问服务数据时遇到困难。
我的TS:
export class ListConditionsComponent implements OnInit {
conditions: Condition[];
fCon: string[];
constructor(private _service: ConditionService,
private _router: Router,
private _route: ActivatedRoute) { }
ngOnInit():void {
this._service.getConditions()
.subscribe(data => this.conditions = data);
this._router.events.subscribe(event => {
if(event instanceof NavigationStart) {
}
if(event instanceof ActivationEnd) {
this.fCon = event.snapshot.queryParams["fCon"];
console.log("actiend fCon:" + this.fCon);
console.log("actiend conditions:" + this.conditions);
}
});
}
}
模板:
<ul>
<li *ngFor="let condition of conditions; let i = index">
<label>
<input type="checkbox" value="{{ condition.Id }}" *ngIf="fCon == condition.Id" checked />
<input type="checkbox" value="{{ condition.Id }}" *ngIf="fCon != condition.Id" />
<span>{{ condition.Name }}</span>
</label>
</li>
</ul>
我的模板已填充,没有任何问题。但是在TS中,console.log表示“活动条件:未定义”。我可以毫无问题地读取fCon变量,但是只有条件变量显示为未定义。我不知道为什么无法在ActivationEnd事件中访问“条件”。
谁知道为什么?谢谢。注意:如果您想知道为什么我要像这样访问queryparams,这是在[router-outlet]中未加载的组件中完成的,因此,我无法访问传统的访问queryparams的方法。
经过数小时的头痛,我发现了我的工作原理
ngOnInit(): void {
this._router.events.subscribe(event => {
if (event instanceof ActivationEnd) {
this.getAllConditions();
}
});
}
async getAllConditions() {
this.conditions = await this._service.getConditions().toPromise();
//from here I can continue as the data will be loaded from hereon
console.log(this.conditions.length); //prints fine the length as the data is loaded
}
再次感谢@Kurt Hamiton指出异步加载,并确保您的代码也对某人有用,这就是为什么我将您的代码标记为答案
每个请求都是异步的,因此您需要通过链接可观察对象来同步调用。如果您的服务电话取决于您的路线,则可以将您的服务电话追加到该路线电话中。根据您的情况,服务呼叫不取决于路线,因此应优先考虑。
export class ListConditionsComponent implements OnInit {
conditions: Condition[];
fCon: string[];
constructor(private _service: ConditionService,
private _router: Router,
private _route: ActivatedRoute) { }
ngOnInit():void {
// first, get the conditions from the service...
this._service.getConditions().pipe(
// now save them to the "conditions" property
tap(data => this.conditions = data),
// now switch to a different observable
concatMap(() => this._router.events)
).subscribe(events => {
// subscribe will receive whatever the last observable in the chain is emitting
if(event instanceof NavigationStart) {
}
if(event instanceof ActivationEnd) {
this.fCon = event.snapshot.queryParams["fCon"];
console.log("actiend fCon:" + this.fCon);
console.log("actiend conditions:" + this.conditions);
}
});
}
}
可观察对象链接在一起,并在管道中进行处理。对于您的情况,您想从服务中获取数据,将其存储在组件中,然后接收所有路由器事件。