如何使用共享服务将数据从一个组件发送到另一个组件 [英] How to send data from one component to another using a shared service

查看:25
本文介绍了如何使用共享服务将数据从一个组件发送到另一个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用主题将数据发送到另一个组件(出于盈利目的).我无法取回数据.这是我的代码:

I wanted to send data using subject to another component (for a earning purpose). I am not able to fetch back the data. Here is my code:

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

}

我没有在控制台中获取值.

I am not getting the value in console.

这是工作演示:DEMO

推荐答案

通过放置:

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

在这两个组件中,您都在创建共享服务的两个不同实例.每个实例并不知道"来自每个组件的数据.在模块级别提供它并创建一个单例服务:

in both components, you are creating two distinct instances of the shared service. Each instance is not 'aware' of the data from each component. Provide it at module level and create a singleton service:

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

通过这种方式,您可以将服务作为单个实例注入到两个组件中,这样它们就可以像共享数据一样共享它.

This way, you inject the service as a single instance in the both components, so they can share it as they will share the data.

或者使用 Angular 的首选新方式:

从 Angular 6.0 开始,创建单例的首选方式service 是在服务中指定它应该在应用程序根.这是通过将 providedIn 设置为 root 来完成的服务的@Injectable 装饰器:

Beginning with Angular 6.0, the preferred way to create a singleton service is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator:

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

演示

参见另见

这篇关于如何使用共享服务将数据从一个组件发送到另一个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆