【发布时间】:2018-02-09 18:59:09
【问题描述】:
我想使用 subject 将数据发送到另一个组件(出于盈利目的)。我无法取回数据。这是我的代码:
app.component.ts
import { Component } from '@angular/core';
import { shareService } from './share.service';
@Component({
selector: 'my-app',
template: `
<hello></hello>
<button (click)="passData()">
Start
</button>
`,
styleUrls: [ './app.component.css' ],
providers:[shareService]
})
export class AppComponent {
constructor(private service : shareService){}
passData(){
this.service.send("hello");
}
}
hello.component.ts
import { Component, Input } from '@angular/core';
import { shareService } from './share.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'hello',
template: `<h1>Hello!</h1>`,
styles: [`h1 { font-family: Lato; }`],
providers:[shareService]
})
export class HelloComponent {
subscription: Subscription;
constructor(private share : shareService){
this.subscription = share.subj$.subscribe(val=>{
console.log(val);
})
}
}
share.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class shareService{
private sub = new Subject();
subj$ = this.sub.asObservable();
send(value: string) {
this.sub.next(value);
}
}
我没有在控制台中获得价值。
这里是工作演示:DEMO
【问题讨论】:
-
如果你想深入了解如何在模块之间共享数据,这会让你感兴趣stackoverflow.com/questions/40089316/…
标签: javascript angular typescript angular-services