關於Angular2元件通訊 自己的一點總結

2022-01-13 06:22:52 字數 1878 閱讀 4383

一、元件之間通訊的方式

使用事件通訊(eventemitter,@output):

// child 元件

@component()

@output() onvoted: eventemitter= new eventemitter();

ngoninit(): void

}// parent 元件

@component()

ngoninit(): void

onlisten(data: any): void

}ps:很討厭貼**,太佔空間了;

2.使用@viewchild和@viewchildren:

// 子元件

@component()

data = 1;

ngoninit(): void

getdata(): void

}

// 父元件

@component()

ngoninit(): void

}

3.使用服務service進行通訊,即:兩個元件同時注入某個服務:

// 元件a

@component()

constructor(private message: messageservice)

ngoninit(): void

}

// 元件b

@component()

constructor(private message: messageservice)

ngoninit(): void

}

二、關於我自己的訊息服務模組

場景:我涉及到乙個專案,裡面需要實現的是所有元件之間都有可能通訊,或者是乙個元件需要給幾個元件通訊。

設計方式:(1). 使用rxjs,定義乙個服務模組messageservice,所有的資訊都註冊該服務;(2). 需要發訊息的地方,呼叫該服務的方法;(3). 需要接受資訊的地方使用,呼叫接受資訊的方法,獲得乙個subscription物件,然後監聽資訊;(4). 當然,在每乙個元件destory的時候,需要this.subscription.unsubscribe();

**:

// 訊息中專服務

@injectable()

export class messageservice );

}/**

* 傳送資訊

* @param src:位址

*/sendimages(src: string) );

}/**

* 清理訊息

*/clearmessage()

/*** 獲得訊息

* @returns 返回訊息監聽

*/getmessage(): observable

}

// 使用該服務的地方,需要註冊messageservice服務;

constructor(private message: messageservice)

// 訊息接受的地方;

public subscription: subscription;

ngafterviewinit(): void )

}// 元件生命週期結束的時候,記得登出一下,不然會卡卡卡卡;

ngondestroy(): void

// 呼叫該服務的方法,傳送資訊;

send():void

總結:這裡的messageservice,就相當於使用廣播機制,在所有的元件之間傳遞資訊;不管是數字,字串,還是物件都是可以傳遞的,而且這裡的傳播速度也是很快的。

Angular 2 元件之間如何通訊

import from angular2 core component class child component i number 0 constructor 1000 import from angular2 core component class child 1000 component i...

關於Angular2元件通訊 自己的一點總結

一 元件之間通訊的方式 使用事件通訊 eventemitter,output child 元件 component output onvoted eventemitter new eventemitter ngoninit void parent 元件 component ngoninit void...

angular2新建元件

1,使用 ng g c hello 建立乙個新的元件 它建立了4個檔案,並更新了 如果想訪問這個元件,只需要新增它的路由 成功訪問這個元件 import語句定義了我們需要用到的哪些模組,import 語句的結構 import from wherever.這種寫法叫解構。解構是 es6和 typesc...