skip to Main Content

I am trying to create a typescript object from an HTTP response in angular8, But I receive an error:

ERROR ReferenceError: Profile is not defined
at SafeSubscriber._next (app.service.ts:17)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next
(Subscriber.js:134)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next
(Subscriber.js:77)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next
(Subscriber.js:54)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next
(map.js:41)

My Profile.ts file is : here
My app.service.ts file is: here

I construct a component class object with this service result and I also get the error

ERROR TypeError: Cannot read property ‘name’ of undefined

when I use it in the HTML file.

The console output for the statement in service file is:

{
  name: "somename",
  status: "sometext",
  bio: "sometext",
  email: "email",
  gitlab: "link",
  twitter: "link",
  instagram: "link",
  linkedin: "link",
  telegram: "link"

},

This is output accompanied by the errors.

My HTML code shortly is :

<p class="ui header">{{profile.name}}</p>

My component class file is: here

2

Answers


  1. The issue is in getProfile() method of your AppService. You are returning this.profile from this method, instead, you should return an observable like this:

    getProfile(): Observable<Profile> {
        return this.http.get(this.profileApiUrl) 
                   .pipe(
                      map(pro => new Profile(pro))
                   );
      }
    

    Now in component inject this service in the component constructor like this:

    //have a class variable
    //this will be used in the template to render the profile
    profile: Profile;
    constructor(private _appService: AppService) {}
    
    ngOnInit() {
     this._appService.getProfile().subscribe(pro => {this.profile = pro;});
    }
    

    Use a safe operator in the template –

    <p class="ui header">{{profile?.name}}</p>
    
    Login or Signup to reply.
  2. You don’t need extra code to map to Profile object. HttpClient would do it for you.
    You need to make few changes to service.ts as below:

    getProfile(): Observable<Profile> {
        this.http.get<Profile>(this.profileApiUrl)
        .pipe(map((pro: any) =>{
          this.profile = pro;
          return pro
        });
      }
    }
    

    In Component:

    ngOnInit() {
     this._appService.getProfile().subscribe(pro => this.profile = pro;);
    }
    

    And in you html:

    <p class="ui header">{{profile?.name}}</p>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search