简体   繁体   English

Angular5服务未发送数据?

[英]Angular5 service not sending data?

My code has 2 components, A and B. A has a form with data in it. 我的代码包含2个组件,A和B。A的表单中包含数据。 I want to send the data from the form in component A to component B. But it looks like B isn't getting any data. 我想将数据从组件A中的表单发送到组件B。但是看来B没收到任何数据。

Component A: 成分A:

 import { MyService } from 'path/myService.service'; @Component({ //blah blah providers: [MyService] }) export class ComponentA implements OnInit { //my form data constructor(private myServ: MyService) {} ngOnInit() { } onChange(event) { const data = event.target.value; this.myServ.changeMessage(data); console.log("sent"); } } 

Component B: 成分B:

 import { Component, OnInit } from '@angular/core'; import { MyService } from 'path/myService.service'; @Component({ // blah blah providers: [MyService] }) export class ComponentB implements OnInit { recievedData = null; constructor(private myServ: MyService) {} // i tried putting this in constructor instead, but it still didn't work ngOnInit() { this.myServ.currentMessage.subscribe(message => { console.log(message); this.recievedData = message }); } } 

My Service: 我的服务:

 import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MyService { private messageSource = new BehaviorSubject(0); currentMessage = this.messageSource.asObservable(); changeMessage(message) { this.messageSource.next(message); } constructor() { } } 

The console.log("sent") fires in Component A's onChange method, but the console.log(message) never fires in Component B's subscribe codeblock. console.log(“ sent”)在组件A的onChange方法中触发,但console.log(message)从不在组件B的订阅代码块中触发。 Any ideas? 有任何想法吗?

You provide MyService (see the providers array in @Component) in each component, so each component has its own instance of the service. 您在每个组件中提供MyService(请参阅@Component中的providers数组),因此每个组件都有其自己的服务实例。 Remove providers from component metadata 从组件元数据中删除提供者

When I've used BehaviorSubject I've needed to subscribe to the observable and specify async and use await on the response. 当我使用BehaviorSubject我需要订阅可观察对象并指定async并在响应中使用await In component b it would look like this for you: 在组件b中,它看起来像这样:

this.toggleService.currentMessage.subscribe(async(message) => 
{
  this.recievedData = await message;
});

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

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