我现在正在研究angular2一段时间了,并且想知道为什么我无法访问ngOnInit()
中的对象,但可以在服务调用中访问它们。
对于前。
import { Component} from 'angular2/core';
import { GlobalService} from './../../app/shared/services/global/global.service';
import { GlobalObjectsService} from './../../app/shared/services/global/global.objects.service';
import { WorkspaceService } from './../../app/shared/services/pm/workspaces.service';
import { ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';
import {ProjectsService} from './../../app/shared/services/pm/projects.service';
import {PagesService} from './../../app/shared/services/pm/pages.service';
import { WorkspacesComponent} from './../../app/project-manager/workspaces/workspaces.component';
import { ProjectsComponent } from './../../app/project-manager/projects/projects.component';
import { PagesComponent } from './../../app/project-manager/pages/pages.component';
@Component({
selector: 'project-manager',
templateUrl: "app/project-manager/project-manager.component.html",
providers: [WorkspaceService,ProjectsService,PagesService],
directives: [ROUTER_DIRECTIVES,WorkspacesComponent,ProjectsComponent,PagesComponent]
})
export class ProjectManegerComponent {
public workspaces: any;
public projects: any;
public pages: any;
baseUrl: string;
constructor(private globalService: GlobalService, private globalObjectsService: GlobalObjectsService,private workspaceService: WorkspaceService,private projectsService:ProjectsService,private pagesService:PagesService) {
this.baseUrl = this.globalService.getBaseUrl();
this.workspaceService.getAllWorkspaces(this.baseUrl)
.subscribe((workspaces) => {
this.workspaces=workspaces;
this.globalObjectsService.selectedWorkspace=workspaces[0];
console.log(this.globalObjectsService.selectedWorkspace);
//able to access here
}
);
this.projectsService.getAllprojects(this.baseUrl)
.subscribe((projects) => {
this.projects = projects;
}
);
this.pagesService.getAllpages(this.baseUrl)
.subscribe((pages) => {
this.pages = pages;
}
);
}
ngOnInit() {
console.log(this.globalObjectsService.selectedWorkspace);
//cannot access here
}
}
所以我很想知道如何在ngOnInit中访问它?
答案 0 :(得分:3)
这是因为this.globalObjectsService.selectedWorkspace
是在订阅回调中异步设置的。在执行ngOnInit
挂钩方法之前,组件不会等待在其构造函数中触发的异步处理完成。
请参阅:
this.workspaceService.getAllWorkspaces(this.baseUrl)
.subscribe((workspaces) => {
this.workspaces=workspaces;
this.globalObjectsService.selectedWorkspace=workspaces[0]; //<------
});
ngOnInit
方法“仅”参与组件生命周期。
修改强>
如果要基于selectedWorkspace
属性触发处理,可以在订阅回调中执行它们:
constructor() {
this.workspaceService.getAllWorkspaces(this.baseUrl)
.subscribe((workspaces) => {
this.workspaces=workspaces;
this.globalObjectsService.selectedWorkspace=workspaces[0];
this.executeSomething(); //<------
});
}
executeSomething() {
console.log(this.globalObjectsService.selectedWorkspace); //<------
}