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();

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

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

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

  constructor() { }

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

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

你可能感兴趣的:(angular)