[英]Unable to get data from http.get via Observable via ngOnInit in Angular
On my component init I'm getting data from the server在我的组件初始化中,我从服务器获取数据
import {Rules} from "../../interfaces/interfaces";
rules: Rules
ngOnInit() {
this.tt = this.rulesService.getUserClientRules().subscribe(
t => {
console.log(t)
console.log(t.clientRules.canAll)
this.rules = t.clientRules
},
error => {
console.log(error.error.message)
}
)
}
My service code is我的服务代码是
getUserClientRules(): Observable<Rules> {
return this.http.get<Rules>('/api/rules/getClientUserRules/')}
and I have interface like:
export interface Rules {
clientRules: any
}
I'm getting response like this:我得到这样的回应:
**{clientRules: {canAll: true, canSee: false}}**
How I can push this object into my rules object?如何将此对象推送到我的规则对象中? I want to use it like rules.canAll or rules.canSeeAll ...
我想像rules.canAll或rules.canSeeAll一样使用它...
and when I try console.log(this.rules) I'm getting undefined当我尝试console.log(this.rules)我变得未定义
I need this strucrure rules { canAll: true, canSee: true } I need to use it for the checks like * ngIf="rules.canSee"我需要这个结构规则{ canAll: true, canSee: true }我需要用它来检查 * ngIf="rules.canSee"
Thank you for your responses!!!谢谢您的反馈!!!
For your requirement the interface should actually look like根据您的要求,界面实际上应该看起来像
export interface Rules {
canAll: boolean;
canSee: boolean;
}
Then you could RxJS map
operator to return the clientRules
property from the HTTP call然后你可以 RxJS
map
运算符从 HTTP 调用返回clientRules
属性
Service服务
getUserClientRules(): Observable<Rules> {
return this.http.get<Rules>('/api/rules/getClientUserRules/').pipe(
map(response => response['clientRules'])
);
}
You could then assign the response directly to the rules
variable in the component然后,您可以将响应直接分配给组件中的
rules
变量
Component成分
rules: Rules
ngOnInit() {
this.tt = this.rulesService.getUserClientRules().subscribe(
t => {
console.log(t);
console.log(t.canAll);
this.rules = t; // <-- the response is already the `clientRules` property
},
error => {
console.log(error.error.message)
}
);
}
You could then use it in the template using the safe navigation operator ?.
然后,您可以使用安全导航操作符
?.
在模板中使用它?.
to avoid unnecessary undefined
errors.避免不必要的
undefined
错误。
Template模板
<div *ngIf="rules?.canSee">
User can see...
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.