Angular5服务未发送数据?

时间:2018-07-12 14:59:38

标签: javascript angular typescript service rxjs

我的代码包含2个组件,A和B。A的表单中包含数据。我想将数据从组件A中的表单发送到组件B。但是看来B没收到任何数据。

组件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");
  }
}

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

我的服务:

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() { }
}

console.log(“ sent”)在组件A的onChange方法中触发,但console.log(message)在组件B的订阅代码块中从未触发。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您在每个组件中提供MyService(请参阅@Component中的providers数组),因此每个组件都有其自己的服务实例。从组件元数据中删除提供程序

答案 1 :(得分:0)

使用BehaviorSubject后,我需要订阅可观察对象并指定async并在响应中使用await。在组件b中,它看起来像这样:

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