全局服务无法在angular2

时间:2016-05-11 06:40:56

标签: javascript typescript angular angular2-services

我在angular2中创建了一个全局服务,用于访问所有组件的变量,如下所示。

global.objects.service.ts

import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import 'rxjs/add/operator/share';

export class GlobalObjectsService {
  workspace:any;     
  constructor() {    
  }  
}

然后我可以访问&在我的workspace.component中为此对象设置新值,如下所示:

import {Component, OnInit,Input} from 'angular2/core';
import { GlobalService} from './../../../app/shared/services/global/global.service';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
import { WorkspaceService } from './../../../app/shared/services/pm/workspaces.service';   

@Component({
    selector: 'workspaces',
    providers:[WorkspaceService],        
    templateUrl: 'app/project-manager/workspaces/workspaces.component.html'
})

export class WorkspacesComponent implements OnInit {
    @Input() workspaces:any;    
    constructor(private globalService:GlobalService,private globalObjectsService:GlobalObjectsService,private workspaceService:WorkspaceService) { }

    ngOnInit() { }    
    selectWorkspace(workspace_id:string){
       this.workspaceService.getWorkspaceById(workspace_id,this.globalService.baseUrl).subscribe((workspace)=>{
           this.globalObjectsService.workspace=workspace; 
           console.log(this.globalObjectsService.workspace);  //this prints workspace correctly        
       });           
    }    
}

但是当我尝试在下面的组件中访问此全局对象时,它显示undefined

import {Component, OnInit ,Input} from 'angular2/core';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
@Component({
    selector: 'pages',    
    templateUrl: 'app/project-manager/pages/pages.component.html'
})
export class PagesComponent implements OnInit {
    @Input() pages:any;
    public workspace:any;    
    constructor(private globalObjectsService:GlobalObjectsService) {
        this.workspace=this.globalObjectsService.workspace; 
        console.log(this.workspace);  //this is not working           
    }
    ngOnInit() { }        
}

我在引导时没有将global.objects.service包含在除根组件之外的任何组件的providers中。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您的服务缺少@Injectable()指令。只需添加如下:

import {Injectable} from 'angular/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import 'rxjs/add/operator/share';

@Injectable()
export class GlobalObjectsService {
  workspace:any;     
  constructor() {    
  }  
}

在Angular 2 here中阅读有关依赖注入的更多信息。

答案 1 :(得分:0)

您似乎缺少的是将WorkspaceService注入GlobalObjectsService

@Injectable()
export class GlobalObjectsService {
  constructor(public workspace:WorkspaceService) {    
  }  
}

您需要提供WorkspaceService之类的GlobalObjectsService。全球GlobalObjectsService无法注入更多本地WorkspaceService,具体取决于您注入的位置GlobalObjectsService