简体   繁体   English

将数据从服务传递到组件

[英]Passing Data from Service to Component

Before someone mark this as duplicate Below are the links that I tried and failed 在有人将此标记为重复之前以下是我尝试过但失败的链接

Angular 2 - passing data from service to component Angular 2 - 将数据从服务传递到组件

How to subscribe to an event on a service in Angular2? 如何在Angular2中订阅服务上的事件?

Scenario I want to sent data from my ng2 service to component and the data is being loaded from an API using ng2 HTTP 场景我想将数据从我的ng2服务发送到组件,并且使用ng2 HTTP从API加载数据

Below is the dummy code 下面是虚拟代码

MyService 为MyService

@Output() event_callback: EventEmitter<any> = new EventEmitter();

getUserDetails(id)
{
    var user_data;
    this.loadRemoteUrl('getUserdata?user_id=' + id).subscribe(
        data => { user_data = data},
        err => console.error(err),
        () => {
            console.log('Inside My Service');
            this.user_data = user_data;
            this.event_callback.emit(this.user_data);
        }
    );
}

MyComponent 为MyComponent

constructor(private http:Http, private myService: MyService) 
{
    var userDetails;
    myService.event_callback.subscribe(
        data => this.callbackFunction()
    );
}

callbackFunction()
{
    console.log("Inside MyComponent")
}

Console Log 控制台日志

Inside My Service

The HTTP request is returning data properly which I tried dumping before emit and it worked but problem is I am unable to access data in my component, I tried passing data,now I am just some logging messages to identify flow but still unable to see the log message from my component file. HTTP请求正确地返回数据我尝试在发出之前进行转储并且它工作但问题是我无法访问我的组件中的数据,我尝试传递数据,现在我只是一些记录消息来识别流但仍然无法看到从我的组件文件中记录消息。

What did I miss? 我错过了什么?

In your case instead of @Output i recommend use observable Subject. 在你的情况下,而不是@Output我建议使用可观察的主题。

In your service, insted of: 在您的服务中,以下内容:

@Output() event_callback: EventEmitter<any> = new EventEmitter();

Create new observable source and stream (Remember to import Subject from "rxjs/Subject"): 创建新的可观察源和流(记住从“rxjs / Subject”导入主题):

private eventCallback = new Subject<string>(); // Source
eventCallback$ = this.eventCallback.asObservable(); // Stream

Insted of: Insted:

this.event_callback.emit(this.user_data);

Send message by: 发送消息:

this.eventCallback.next(this.user_data);

And then, in your component: 然后,在您的组件中:

myService.eventCallback$.subscribe(data => {
    this.callbackFunction();
});

See: working example on Plunker 请参阅: Plunker上的工作示例

Read more about this solution: Angular.io - Communicate via a service 阅读有关此解决方案的更多信息: Angular.io - 通过服务进行通信

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM