-1

When I am updating my html with the response Obj using HttpClient it updates the values but gives multiple errors.

File Name - auth-service.ts.

    import { any } from 'codelyzer/util/function';
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';

    @Injectable()
    export class AuthService {

      constructor(private httpClient: HttpClient) { }
      get() {
        return this.httpClient.get<any>('/capi/v2/users/me', {
          observe: 'body',
          responseType: 'json'
        });
      }
    };

File Name - dashboard.component.ts

    import { AuthService } from './../../services/api/auth-service';

    import { Component, Injectable, OnInit } from '@angular/core';

    @Component({
        selector: 'app-dashboard',
        templateUrl: './dashboard.component.html'
    })

    @Injectable()
    export class DashBoardComponent implements OnInit {
        user;
        constructor(private authService: AuthService) {};

        ngOnInit() {
             this.authService.get()
            .subscribe(
              (response) => {
                  this.user = response;
              }
            );
        }
    }

The Response Obj is

{
    "firstName": "xyz",
    "lastName": "abc",
    "active": true
}   

File Name - dashboard.component.html

<div class="container-fluid text-center">
<h1 class="bold m-t m-b-xs">Hey there!</h1>
<h3 class="m-b">How are you doing today?</h3>

{{ user.active }}

<div class="block clear m-a">&nbsp;</div>

    <div class="row m-t p-t">
        <div class="col-xs-12"> </div>
    </div>
</div>

Details about errors in console:

are described here.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
atul mishra
  • 253
  • 1
  • 6
  • 20

2 Answers2

5

Your error is likely because Angular attempts to evaluate user.active before the get request completes.

You can update {{ user.active }} to include a ? (known as the safe navigation operator):

{{ user?.active }}

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths.

You could instead use ngIf to avoid rendering your container until the data is retrieved. i.e.:

<div class="container-fluid text-center" *ngIf="user">
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
0

You need to use map function to return response to component. Replace this code with you service get.

get() {
  return this.httpClient.get<any>('/capi/v2/users/me')
    .map((resp) => resp)
    .catch((error) => error);
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Rohan Fating
  • 2,135
  • 15
  • 24
  • Also after adding the map m getting this error in addition - core.es5.js:1020 ERROR TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. – atul mishra Sep 08 '17 at 14:32