我现在花了相当长的时间来研究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中使它可访问?
这是因为this.globalObjectsService.selectedWorkspace
是在订阅回调中异步设置的。在执行ngOnInit
hook方法之前,组件无需等待其构造函数中触发的异步处理完成。
看:
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); //<------
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句