簡體   English   中英

如何從Angular 7中的Observable返回對象

[英]How to return object from Observable in Angular 7

我在Angular 7和RxJS@6.3.3上有一個應用程序。 我試圖從Observable對象獲取價值,但我不知道為什么它不返回。

有我的示例代碼: https : //stackblitz.com/edit/angular-w9ftkw

在我的示例html文件中,我得到了:

<hello name="{{ result.property1 }} {{ result.property2 }} {{ result.property3 }} {{ resultIsUndefined }}"></hello>
<p>
  {{err}}
</p>

但我的結果的屬性( {{ result.property1 }} {{ result.property2 }} {{ result.property3 }} )不顯示。

怎么了

我嘗試返回的res對象仍然是Observable類型。 我試圖將其投射到MyResponseClasss但沒有效果。

這是我真正的問題。 為什么返回的對象仍然是Observable類型。

在這部分代碼上:

if (result) {
  result.subscribe((result: MyResponseClass) => {
    this.resultIsUndefined = false;
    res = result;
    console.log(res);
  })
  return res;
}

我想要一個數據類型為MyResponseClassres

您要做的就是添加json管道。

像這樣:

{{ err | json}}

或者,如果您確切知道要使用的對象內部的哪個屬性,則示例:

{{err.message}}

當您的數據來自Observable時,您應該考慮使用異步管道{{ 異步}}

閱讀更多:

您需要對json對象進行字符串化處理才能以html格式顯示。 像這樣

let result = this.http.request("get", url_, options_).pipe(
map((response_: any) => this.test(response_)),
catchError((err: any, caught: Observable<any>) => {
**this.err = JSON.stringify(err);**
if (caught instanceof Response) {
try {
   return this.test(caught);
} catch (e) {
return of<MyResponseClass | null>(<any>throwError(e));
}
} else
  return of<MyResponseClass | null>(<any>throwError(caught));
})
);

我解決了我的問題。 可通過兩種方式創建可觀察對象:

  • 通過使用Observable <T>作為異步
  • 通過使用<T>進行同步

我的問題是我在異步應用程序上將Observable對象創建為同步對象。 就這樣。

您正在從這次考核中得到回應。

protected test(response: Response): Observable<MyResponseClass>{};

在此課程中,您需要致電http服務電話。

protected test(response: Response): Observable<MyResponseClass>{
this.http.get(url,options);
};

然后,您需要在ts類中訂閱觀察者。

export class AppComponent  {
err: string;
resultIsUndefined: boolean;
http: HttpClient;
result: MyResponseClass;
name: string;
constructor(@Inject(HttpClient) http: HttpClient) {
this.http = http;
this.result = this.get();
}
protected test(): Observable<MyResponseClass> { 
let result = new MyResponseClass();
result.property1 = "Mr";
result.property2 = "John";
result.property3 = "Kowalsky";
return of<MyResponseClass>(result); 
}
get(): MyResponseClass {
let res = new MyResponseClass();
let url_ = '';
let options_: any = {
method: "get",
headers: new Headers({
"Content-Type": "application/json",
"Accept": "application/json"
})
};
this.test().subscribe(res =>{
this.name = res.property1 + res.property2 + res.property3;
console.log(res, this.name);
},
error=>{
this.err = JSON.stringify(error);
console.log(error);
})
this.resultIsUndefined = true;
return <MyResponseClass>null;
}
}

在app.component.html中,它必須像這樣

<hello [name]="name"></hello>
<p>
{{err}}
</p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM