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

问题描述 投票:3回答:2

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

angular typescript angular-services
2个回答
6
投票

通过:

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

在这两个组件中,您将创建共享服务的两个不同实例。每个实例都不“了解”每个组件的数据。在模块级别提供它并创建单例服务:

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

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

或使用Angular's preferred new way

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

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

Demo

also


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

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

© www.soinside.com 2019 - 2024. All rights reserved.