简体   繁体   中英

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 ...

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!!!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM