如何使用共享服务将数据从一个组件发送到另一个组件

问题描述:

我想使用主题将数据发送到其他组件(用于赚钱目的)。我无法取回数据。这里是我的代码:如何使用共享服务将数据从一个组件发送到另一个组件

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://*.com/questions/40089316/how-to-share -service-between-two-modules-ngmodule-in-angular2 –

通过将:

@Component({ 
    ..... 
    providers: [shareService] 
}) 
在这两个组件

,你所创建的共享servcie的两个不同的实例。 每个实例都不知道每个组件的数据。 在模块级提供,它会工作。

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

这样,您将服务作为单个实例注入到这两个组件中,以便它们可以共享它,因为它们将共享数据。

demo

also

+0

听起来不错 – yurzui

+0

但是,如果我分别在每个组件中提供它,它应该工作吗? – Sampath1504

+0

谢谢!有效 。 – Sampath1504

我不知道为什么被用于子$,但你不需要是

// 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://*.com/questions/36986548/when-to-use-asobservable-in-rxjs是一个很好的做法,只通过可观察的接口 –

+0

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

+0

我从来没有使用过。我解释的方式我alwasy使用它。对于我来说,它的额外的代码行,并且需要你的组件(客户端)只关心它的可观察的行为 –