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

时间:2017-08-31 18:26:51

标签: angular typescript angular-services

我想使用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

2 个答案:

答案 0 :(得分:5)

提出:

@Component({
  .....
  providers: [sharedService]
})

在两个组件中,您将创建共享服务的两个不同实例。 每个实例都不会意识到&#39;来自每个组件的数据。 在模块级别提供它并创建单件服务:

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

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

或使用Angular's preferred new way

  

从Angular 6.0开始,这是创建单例的首选方法   service是指在服务上指定它应该提供的   应用程序根。这是通过将provideIn设置为root来完成的   服务的@Injectable装饰者:

@Injectable({
  providedIn: 'root',
})

Demo

请参阅also

答案 1 :(得分:0)

我不知道为什么使用sub $但你不需要那个

// 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);
    })
  }
} 

确保以模块级别提供服务或在组件中提供服务。

相关问题