angular項目中實現rxjs訂閱

getMessage.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonService } from '../services/common.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, OnDestroy {
  list: any;
  title: string;
  message = 'scotter';
  test: string;
  subscription: Subscription;

  constructor(
    private commonService: CommonService
  ) {
    this.list = commonService.dateList;
    this.title = commonService.content;
    this.subscription = this.commonService.getMessage().subscribe(message => {
      console.log(message);
      if (message) {
        this.message = message.data;
      } else {
        this.message = null;
      }
    });
  }

  ngOnInit() {

  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  getCommonContent() {
    console.log(this.message);
  }

}

sendMessage.ts

import { Component, OnInit } from '@angular/core';
import { CommonService } from '../services/common.service';

@Component({
  selector: 'app-new',
  templateUrl: './new.component.html',
  styleUrls: ['./new.component.scss']
})
export class NewComponent implements OnInit {

  constructor(
    private commonService: CommonService
  ) { }

  ngOnInit() {
  }

  sendMessage(): void {
    // send message to subscribers via observable subject
    this.commonService.sendMessage('我是改變後的內容');
  }

  clearMessage(): void {
      // clear message
      this.commonService.clearMessage();
  }


}

commonService.ts

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

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  public content = 'haha';
  public dateList: any = [
    {
      name: '張旭超',
      age: 20,
      address: '北京市朝陽區'
    }
  ];
  test1 = '我是test數據';

  private subject = new Subject<any>();

  sendMessage(message: Object) {
    this.subject.next({ data: message });
  }

  clearMessage() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }

  constructor() { }

  addDateFun(data: any) {
    this.dateList.push(data);
  }

  changeContent(str: any) {
    this.content = str;
    console.log(this.content);
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章