简体   繁体   中英

Angular : passing data between components using service

I work on Angular 4, onclick of one of the 'groups' its tile should be added to the list of 'favourites' (which is an array). For this I used BehaviorSubject . I am able to display default message on my FavouriteComponent.html but when I click on newMessage() from GroupComponent.ts the value in FavouriteComponent.html is not changing it remains default message . Please guide me where I went wrong or is there any other way to achieve my requirement.

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")
  }

}

删除currentMessage并订阅messageSource (将其公开)

Try this.

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")
  }

}

Hope This helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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