我想使用主題將數據發送到其他組件(用於賺錢目的)。我無法取回數據。這裏是我的代碼:如何使用共享服務將數據從一個組件發送到另一個組件
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
如果你想深入下去,看看數據模塊之間共享,這將你感興趣https://stackoverflow.com/questions/40089316/how-to-share -service-between-two-modules-ngmodule-in-angular2 –