Search code examples
angularapiangular2-services

How to GET API data from server in Angular App?


I have problem with write data in component. I write objects data in console but i don't know how to data get to component from objects. This data I GET from server to console: IMAGE. I need extract object data or something other?

In the console I have this ERROR: ERROR TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Do you know how resolve this? Thank you for your help.

My code: app.component.ts

codeLists: CodeLists[] = [];
    
    
      constructor(
        private codeListService: CodeListService,
        private codeListsAdapter: CodeListsAdapter,
      ) { }
    
      ngOnInit(): void {
        this.getCodeLists();
      }
    
      public getCodeLists() {
        this.labService.getAllLists().subscribe(response => {
          this.codeLists = [];
          console.log(response);
          from(response).subscribe((CodeListsRaw: CodeLists) => {
              this.codeLists.push(this.codeListsAdapter.adapt(CodeListsRaw));
            });
        });
      }
    }

app.component.html

<div *ngFor="let list of codeLists">
  <mat-card>
    <mat-card-title>{{list.id}}</mat-card-title>
    <h1>{{list.name}}</h1>
  </mat-card>
</div>

code-list.service.ts

getAllLists(){
    return this.http.get<any>(environment.ApiUrl + `/api/url`);
  }

codelists.ts - model

export class CodeLists {
   id: string;
   name: string;
}

Solution

  • Actually you don't need to subscribe to the response.

    The response is your object, not an observable. Moreover, you can use destructuration. Try this :

    public getCodeLists() {
      this.labService.getAllLists().subscribe(({ codeLists, productList }) => {
        console.log(codeLists, productList);
        codeLists.codeLists.map(codeList => // I edited this line
          this.codeLists.push(this.codeListsAdapter.adapt(codeList)));
      }
    }
    

    More infos on Destructuration here : https://basarat.gitbook.io/typescript/future-javascript/destructuring