2016-11-30 79 views
2

我需要从服务1的数据传递到服务2Angular 2有没有办法在服务之间传递数据?

服务1

@Injectable() 
export class Service1 { 
    ... 
} 

对于服务2

与服务2,我发现,使服务1的唯一方式进行通信是使用窗口['变种类似'](在Service1中设置,在Service2中读取)

我认为这比一个真正的解决方案更“黑客”,但注入第三个服务不起作用。

另一种解决方案是使用localStorage,但对我来说似乎并不理想。

任何线索?

回答

1

您可以直接注入一个服务到另一个

@Injectable() 
class Service2 { 
    // constructor(private service2:Service2) {} 
    // cyclic dependencies are not supported 
    // therefore only one service can inject the other, 
    // but both directions at the same time causes an exception 

    someProp:String = 'xxx'; 
} 

@Injectable() 
class Service1 { 
    constructor(private service2:Service2) { 
    console.log(service2.someProp); 
    } 
} 

参见DI with cyclic dependency with custom HTTP and ConfigService

您还可以使用可观,这样一个服务可以订阅的其他服务的变化。

相关问题