如何使用共享服务将数据从一个组件发送到另一组件 [英] How to send data from one component to another using a shared service
问题描述
我想使用主题发送数据到另一个组件(用于赚钱).我无法取回数据.这是我的代码:
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.
这是正在运行的演示:演示
Here is the working Demo : 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开始,这是创建单例的首选方式 服务是在服务上指定应在 应用程序根目录.这是通过将providerIn设置为根目录上的 服务的@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屋!