0

I'm new to functional programming. While passing function to another function in type script, I'm getting error. Here is my code: -

export class NavigationComponent implements OnInit {

  constructor(public globals: Globals, public auth: AuthService, public placeService: PlaceService) {
    auth.handleAuthentication();
    if (auth.isAuthenticated) {
      console.log(' userName ' + this.firstName + ' userName ' + this.userName + ' dp ' + this.dpUrl);
      this.fetchProfile();
      console.log(' userName ' + this.firstName + ' userName ' + this.userName + ' dp ' + this.dpUrl);
    }
  }

  ngOnInit() {
    this.getCountries();
  }

  private firstName: any;
  private userName: any;
  private dpUrl: any;

  private fetchProfile() {
    this.auth.getProfileReponse(this.processResponse);
  }

  public processResponse(userResponse: Observable<HttpResponse<UserResp>>) {
    userResponse.subscribe(resp => {
      const user: User = { ...resp.body }.flatUser;
      console.log('user');
      console.log(user); // printing user perfetcly
      console.log(user.firstName); // printing user perfetcly
      this.firstName = user.firstName; // facing error here
      this.userName = user.userName;
      this.dpUrl = user.dpURL;
      // console.log(this.flatUser);
    });
  }
}

Error is as below:-

core.js:2090 ERROR TypeError: Cannot set property 'firstName' of undefined
at SafeSubscriber.eval [as _next] (navigation.component.ts:83)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
at SafeSubscriber.next (Subscriber.js:187)
at Subscriber._next (Subscriber.js:128)

why this 'firstName' of undefined, I'm using angular 6 beta version. Please help me to resolve this issue.

1

1 Answer 1

1

It's actually the context of this that is undefined. Try this instead:

this.auth.getProfileReponse(() => this.processResponse);

The arrow syntax will bind to this, and it should prevent the error

Sign up to request clarification or add additional context in comments.

1 Comment

it worked baba, you are beautiful. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.