我已经有了角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
。
所有你需要做的就是添加JSON管。
像这样:
{{ err | json}}
或者,如果你知道你想要什么属性的对象内使用它例如:
{{err.message}}
你需要字符串化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));
})
);
我解决我的问题。观察的对象可以在两种方式创建:
我的问题是,我创建的观察对象作为异步应用同步。就这样。
你都可以从这个类的响应。
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>