如何从可观测的角7返回对象

问题描述 投票:-1回答:5

我已经有了角7和[email protected]一个应用程序。我想从我的可观察对象中获取价值,我不知道为什么它不返回。

还有就是我的示例代码: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;
}

我想有res的数据类型的MyResponseClass

angular observable angular7 rxjs6
5个回答
1
投票

所有你需要做的就是添加JSON管。

像这样:

{{ err | json}}

或者,如果你知道你想要什么属性的对象内使用它例如:

{{err.message}}

0
投票

当你的数据来自可观察你应该考虑使用异步管{{什么|异步}}

更多阅读:


0
投票

你需要字符串化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));
})
);

0
投票

我解决我的问题。观察的对象可以在两种方式创建:

  • 通过使用异步可观察<T>
  • 通过使用的同步<T>

我的问题是,我创建的观察对象作为异步应用同步。就这样。


0
投票

你都可以从这个类的响应。

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>
© www.soinside.com 2019 - 2024. All rights reserved.