Kippet
Kippet

Reputation: 169

HTML Not Rendering Data From Get Request

I load the data on ngOnInit()


  ngOnInit(): void {
    this.http.get<any>(this.ROOT_URL + this.cookieService.get('cookie-name')).subscribe(
      function(res) {
        this.tableData = res.atVendor;
        console.log(this.tableData);
        this.ready = true;

      } ,
      (err) => console.log(err)
    )

I render the data like so:

<div *ngIf="ready">
    <ul><li *ngFor="let obj of tableData"> {{obj}}</li></ul>
</div>

I expect: An array to be displayed as a list. What I get: Nothing being rendered - no errors.

I know that the API call is working because it displays with

console.log(this.tableData)

like so:

0: "Spa" 1: "Apple" 2: "Gamestop" length: 3 proto: Array(0)

I believe the problem is still that the page is rendering before the data is finished being collected from the call, so I tried using ready and then the *ngIf but that made no difference.

Upvotes: 1

Views: 237

Answers (1)

CouchCode
CouchCode

Reputation: 305

You can use pipe map to do your logic and subscribe to the observable. I separated out the http call into its own method as that is both cleaner and standard practice. This approach should map the results of the observable without waiting on the subscription.

 private getCookie(cookieName: string): Observable<any> {
     return this.http.get<any>(this.ROOT_URL + this.cookieService.get(cookieName))
       .pipe(catchError(err => console.error(error)))
 }

 ngOnInit(): void {
     this.getCookie("cookie-name")
      .pipe(map( res => {
          this.tableData = res.atVendor;
          console.log(this.tableData);
          this.ready = true;
      }));
      .subscribe();
)

Upvotes: 2

Related Questions