Reputation: 423
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...
and when I try console.log(this.rules) I'm getting undefined
I need this strucrure rules { canAll: true, canSee: true } I need to use it for the checks like *ngIf="rules.canSee"
Thank you for your responses!!!
Upvotes: 1
Views: 52
Reputation: 31105
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
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
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.
Template
<div *ngIf="rules?.canSee">
User can see...
</div>
Upvotes: 1