angular4+rxjs訂閱發佈者模式實現組件中通訊

1、首先引入rxjs  使用npm install rxjs --savecss

2、建立一個訂閱發佈者的中間件即middlereService 在service中引入rxjs       import {Observable,Subject} from "rxjs";html

eg:示例npm

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

3、在 app.module.ts中進行注入,做爲服務提供者。json

eg:
//「**」爲重點

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

@NgModule({

providers: \[

MyHttp,

**    MessageService,**

UserService

\],

entryComponents: \[ModalComponent\],

bootstrap: \[AppComponent\]

})

export class AppModule { }

4、app.component.ts中進行初始化賦值給window對象,變爲一個全局的對象就能夠在全app,進行使用,而不用每次使用時要import引入一個serviceredux

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)bootstrap

**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)**

**  }**

**}**

6、在另外一個F組件獲取window['transSrv']的值app

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

**        this.stepType = result+'';**

**        console.log("srv3",result)**

**       this.getTask(this.stepType)**

**    })**

eg:ide

/**函數

* 任務具體步驟 下面組件其實有三種解決方法的雛形,一種基於redux思想的ngrx利用action,store,reducer,其實也是另類的訂閱發佈者模式而已,第二種是訂閱發佈模式就是本模式,第三種屬性傳值加利用ngAfterViewChecked周期函數。this

* */

//導入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)

}

}
相關文章
相關標籤/搜索