一、首先引入rxjs  使用npm install rxjs --save

二、创建一个订阅发布者的中间件即middlereService 在service中引入rxjs       import {Observable,Subject} from "rxjs";

eg:示例

import {Injectable} from "@angular/core"; //angular核心依赖注入

import {Observable,Subject} from "rxjs"; //引入rxjs的对象  subject是一个攻受一体的对象,Observable是观察者,subscribe,是订阅者,注,记得z在destory周期函数里解约unsubscribe

@Injectable()

export class MessageService {

    private subject = new Subject<any>();

  /* ngOnInit() {

    window['subject']=subject

   }*/

    send(message: any) {

        this.subject.next(message);

    }

    get(): Observable<any> {

        return this.subject.asObservable();

    }

}

三、在 app.module.ts中进行注入,作为服务提供者。

eg:

import { MessageService } from './service/data/transChange';

@NgModule({

 providers: [

    MyHttp,

    MessageService,

    UserService

  ],

  entryComponents: [ModalComponent],

  bootstrap: [AppComponent]

})

export class AppModule { }

四、app.component.ts中进行初始化赋值给window对象,变为一个全局的对象就可以在全app,进行使用,而不用每次使用时要import引入一个service

eg:

import {Component, OnInit} from '@angular/core';

import {Router} from '@angular/router';

import {getInfo} from '../common/util/utils';

import {Store} from '@ngrx/store';

import { MessageService } from './service/data/transChange';

@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})

export class AppComponent implements OnInit {

  title = 'app';

  constructor(private router: Router, private store: Store<object>,private srv:MessageService) {

    router.events.subscribe(e => {

      const acct = getInfo('ACCOUNT');

      if (acct) {

        if (!/home/.test(e['url'])) {

          router.navigate(['/home']);

        }

      } else {

        if (/home/.test(e['url'])) {

          router.navigate(['/login']);

        }

      }

    });

    window['transSrv']=srv

    console.log("srv1",srv)

  }

  ngOnInit() {

    const acct = getInfo('ACCOUNT');

    window['indextype']=null;

    window['contentType']=null;

    if (acct) {

      this.store.dispatch({type: 'SET', payload: JSON.parse(acct)});

    }

  }

}

伍、在组件中更新window['transSrv']这个值,即在一个M组件window['transSrv'].send(type)

eg:

import { Component, OnInit } from '@angular/core';

// import {TaskContent} from './content/index'

export class jsonArr {

  id:string;

  status:string;

  title:string;

};

let navDetailData: jsonArr[]= [

{id:'一',status:'进行中',title:'资料上传'},

{id:'二',status:'未开始',title:'预审批'},

{id:'三',status:'未开始',title:'初审'},

{id:'四',status:'未开始',title:'实地尽调'},

{id:'五',status:'未开始',title:'终审'},

{id:'六',status:'未开始',title:'合同上传'},

{id:'七',status:'未开始',title:'合同签署'}];

@Component({

  selector: 'app-task-detail',

  templateUrl: './task-detail.component.html',

  styleUrls: ['./task-detail.component.css']

})

export class TaskDetailComponent implements OnInit {

  /*constructor(private srv:MessageService ) { //如过要使用MessageService就得使用import注入他

    console.log('srv2',window['transSrv']);

  } */

  indeType :string;

  flag: boolean = false;

  steps=navDetailData;

  srv: any=window['transSrv'];//将window['transSrv']赋值给srv成为工程对象

  ngOnInit() {

    console.log(this.steps)

     console.log('srv2',window['transSrv']);

    let active=2//正在激活的小任务

    this.change(active)

  }

  showMenu() {

    this.flag = !this.flag;

  }

  change(type) {

    this.indeType = type; //下面两者都可以

     // window['transSrv'].send(type)

     this.srv.send(type)

  }

}

六、在另一个F组件获取window['transSrv']的值

this.srv.get().subscribe((result) => {

        this.stepType = result+'';

        console.log("srv3",result)

       this.getTask(this.stepType)

    })

eg:

/**

* 任务具体步骤 下面组件其实有三种解决方法的雏形,一种基于redux思想的ngrx利用action,store,reducer,其实也是另类的订阅发布者模式而已,第二种是订阅发布模式就是本模式,第三种属性传值加利用ngAfterViewChecked周期函数。

* */

//导入ngex相关

import {Store} from '@ngrx/store';

import *as  fromModal from '../../../../store/modal.reducer'

import *as  modal from '../../../../actions/modal.action'

import { Component, OnInit, Input } from '@angular/core';

// import { Observable, Subscription } from 'rxjs';

@Component({

  selector: 'task-content',

  templateUrl: './content.html',

  styleUrls: ['./content.css']

})

/*const stepNodes :Array<any>=[{

  title:'资料录入',

  details:'请准确填写贷款人资料并上传文件。'

  },{

  title:'预审批',

  details:'请根据上传资料进行预审批并填写推荐额度。'

  },{

  title:'初审',

  details:'请根据贷款资料进行初步审批。'

  },{

  title:'实地尽调',

  details:'请根据贷款资料进行现场核实。'

  },{

  title:'终审',

  details:'请根据贷款资料进行终审并明确融资要素。'

  },{

  title:'合同上传',

  details:'请根据审核结果将生成的合同文件上传至平台。'

  },{

  title:'合同签署',

  details:'请打印合同并由贷款人签字后上传至平台。'

  }]*/

export class TaskContent implements OnInit {

  statusFlag:boolean=true

 taskData: any = {

    createTime: '2017-11-14',

    TASK_FNAME: '国资小贷公会-村分会',

    TASK_CLS:'国资小贷任务',

    TASK_DESCRIBE:'昆明村国资小贷任务',

    TASK_STAT: 0//0-未发布、1-已发布、2-已结束、3-暂停、4-已中止

  };

   stepNodes :Array<any>=[{

  title:'资料录入',

  details:'请准确填写贷款人资料并上传文件。'

  },{

  title:'预审批',

  details:'请根据上传资料进行预审批并填写推荐额度。'

  },{

  title:'初审',

  details:'请根据贷款资料进行初步审批。'

  },{

  title:'实地尽调',

  details:'请根据贷款资料进行现场核实。'

  },{

  title:'终审',

  details:'请根据贷款资料进行终审并明确融资要素。'

  },{

  title:'合同上传',

  details:'请根据审核结果将生成的合同文件上传至平台。'

  },{

  title:'合同签署',

  details:'请打印合同并由贷款人签字后上传至平台。'

  }];

  stepType :string=null;

  srv: any=window['transSrv'];

  @Input() type:string;

  // constructor() { }

  constructor(

    private store: Store<fromModal.State>

  ) {

    // console.log(store)

  }

  ngOnInit() {

    this.srv.get().subscribe((result) => {

        this.stepType = result+'';

        console.log("srv3",result)

       this.getTask(this.stepType)

    })

    console.log(this.type)

   /* console.log("a",this.store)

    console.log(fromModal)

    this.stepType=this.type

    this.handleOpenModal('OPEN_MODAL')*/

    // const pathname = window.location.pathname;

    // this.type = /claim/.test(pathname) ? 2 : /mgr/.test(pathname) ? 1 : 0;

  }

/*ngAfterViewChecked(){

  if(window['indextype']!=this.type){

    window['indextype']=this.type

    console.log("change",this.type)

    setTimeout(()=>{

     this.getTask()

     },2)

 }

}*/

  /*change(type) {

    this.type = type;

  }*/

  // 调用 action 以开启模态框

  handleOpenModal(modalName) {

     console.log("1212121212",modalName)

    // this.store.dispatch(new modal.OpenModalAction(modalName));

    this.store.dispatch({type: "aa OPEN_MODAL",payload:'打开'})

    console.log(modalName)

  }

  // 调用 action 以关闭模态框

/*  handleCloseModal() {

    this.store.dispatch(new modal.CloseModalAction());

  }*/

  getTask(obj){

  let me=this

  let metype=parseInt(obj)

  if(metype==0){

    this.stepType='msg'

  }else if(metype>=1&&metype<=4){

    this.stepType='approve'

  }else{

     this.stepType='agree'

  }

}

getTask1(){

  let me=this

  let metype=parseInt(me.type)

  if(metype==0){

    this.stepType='msg'

  }else if(metype>=1&&metype<=4){

    this.stepType='approve'

  }else{

     this.stepType='agree'

  }

  this.statusFlag=false

  console.log(this.stepType)

}

}

05-17 17:08