[英]How to send data from one component to another via observable and display the data in the secound html template in Angular
您好,我正在嘗試在單擊事件上將對象從 1. Component 發送到 2. Component。 目前,我使用具有獲取和設置功能的數據服務來嘗試此操作:
setDataObject(obj) {
this.subject.next(obj)
}
getDataObject(obj): Observable <any> {
return this.subject.asObservable()
}
在 1. 組件上,我在 cliick 事件上觸發 setDataObject(obj)。 在 2. Component 我現在不確定如何正確訂閱 Observable 並且可以將對象從 1.Component 保存到另一個變量。 但我讀到你不應該那樣使用可觀察的。 那么如何在我的 HTML 模板中顯示對象及其屬性呢? 我已經嘗試過:
*ngIf = "observable$ | async as myObj"
但是雖然我的 console.log 顯示了 obj,但它沒有顯示在模板中。
這是一個簡單的示例,說明如何在基本服務中設置 observable,然后從另一個組件訂閱它。
從 observable 接收值后,您可以使用異步管道 observable 在調用組件的 HTML 模板中顯示它。
Service
TS
@Injectable()
export class Service {
subject: Subject<number> = new Subject();
setDataObject(obj) {
this.subject.next(obj);
}
getDataObject(): Observable<any> {
return this.subject;
}
}
Client Component
TS
下面的代碼我們在不訂閱它的情況下初始化異步 observable,並提供了一種方法來使用隨機數在服務中設置 observable 的值。
export class AppComponent {
displayObservable$: Observable<number>;
constructor(private api: Service) {
this.displayObservable$ = api.getDataObject().pipe(
map((res) => {
console.log('value from service = ' + res);
return res;
})
);
}
sendValue(val: any) {
let num: number = Math.floor(Math.random() * 100);
console.log('value sent to service = ' + num);
this.api.setDataObject(num);
}
}
HTML
以下 HTML 包含一個按鈕,用於向服務分派值,以及一個用於顯示響應的async
observable:
<div>Value from service = {{ displayObservable$ | async }}</div>
<p>
<button
type="button"
class="btn btn-primary"
id="btnSendValue"
(click)="sendValue($event)">
Send a value to service
</button>
</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.