2017-08-31 93 views
3

我想使用主題將數據發送到其他組件(用於賺錢目的)。我無法取回數據。這裏是我的代碼:如何使用共享服務將數據從一個組件發送到另一個組件

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

+1

如果你想深入下去,看看數據模塊之間共享,這將你感興趣https://stackoverflow.com/questions/40089316/how-to-share -service-between-two-modules-ngmodule-in-angular2 –

回答

4

通過將:

@Component({ 
    ..... 
    providers: [shareService] 
}) 
在這兩個組件

,你所創建的共享servcie的兩個不同的實例。 每個實例都不知道每個組件的數據。 在模塊級提供,它會工作。

@NgModule({ 
    .... 
    providers: [shareService] 
}) 

這樣,您將服務作爲單個實例注入到這兩個組件中,以便它們可以共享它,因爲它們將共享數據。

demo

also

+0

聽起來不錯 – yurzui

+0

但是,如果我分別在每個組件中提供它,它應該工作嗎? – Sampath1504

+0

謝謝!有效 。 – Sampath1504

0

我不知道爲什麼被用於子$,但你不需要是

// just push data to subject. you can use BehavourSubject to initiatte a value. 
@Injectable() 
export class shareService{ 

    private sub = new Subject(); 

    confirmMission(astronaut: string) { 
    this.sub.next(astronaut); 
    } 

} 

,然後在第二組件子隸之

@Component({ 
    selector: 'hello', 
    template: `<h1>Hello!</h1>`, 
    styles: [`h1 { font-family: Lato; }`], 
    providers:[shareService] // this can be shared in module lebel or componenet level 
}) 
export class HelloComponent { 
    subscription: Subscription; 
    constructor(private share : shareService){ 
    this.subscription = share.subj.subscribe(val=>{ 
    console.log(val); 
    }) 
    } 
} 

確保在模塊級別提供服務或在組件中提供服務。

+0

https://stackoverflow.com/questions/36986548/when-to-use-asobservable-in-rxjs是一個很好的做法,只通過可觀察的接口 –

+0

所以使用asObservable是好的嗎? – Sampath1504

+0

我從來沒有使用過。我解釋的方式我alwasy使用它。對於我來說,它的額外的代碼行,並且需要你的組件(客戶端)只關心它的可觀察的行爲 –

相關問題