Angular:使用服务

时间:2018-05-17 07:17:42

标签: angular typescript

我在Angular 4上工作,点击其中一个'组',其瓷砖应添加到'favorites'列表中(这是一个数组)。为此,我使用了BehaviorSubject。我可以在default message上显示FavouriteComponent.html,但当我点击GroupComponent.ts中的newMessage()时,FavouriteComponent.html中的值不会更改,它仍为default message。请指导我哪里出错或有其他方法可以达到我的要求。

DataService.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

FavouriteComponent.ts

import { DataService } from "../data.service";
@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `
})
export class FavouriteComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

GroupComponent.ts

import { DataService } from "../data.service";
@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class GroupComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("new title to add")
  }

}

2 个答案:

答案 0 :(得分:0)

删除currentMessage并订阅messageSource(公开)

答案 1 :(得分:0)

试试这个。

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class DataService {

  private messageSource = new Subject<String>();

  constructor() { }

  public getMessage(): Observable<String> {
    return this.messageSource.asObservable();
  }

  public setMessage(message: String) {
    return this.messageSource.next(message);
  }

}
export class FavouriteComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getMessage.subscribe(message => this.message = message)
  }

}
export class GroupComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.setMessage("new title to add")
  }

}

希望这会有所帮助