Jawad Jawad - 1 year ago 333
TypeScript Question

angular 2 Unhandled promise rejection TypeError

I'm new to angular and typescript. I'm getting error "Unhandled promise rejection TypeError: Cannot set property"

here is my code:


export class LoginComponent implements OnInit {

constructor(private fb: FormBuilder, private loginService: LoginService) { }

submitError = false; // set "true" to show error


this.submitError = false;
this.submitErrorText = "";
this.model = this.loginForm.value;
this.loginService.authenticate(this.model.login_id, this.model.password)
.then(res => {

if(res.status == 404){

this.submitError = true;

// do something

}).catch(function(err: any){

this.submitError = true; // Unhandled promise rejection TypeError: Cannot set property 'submitError' of undefined




import {Injectable} from '@angular/core';
import { Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

export class LoginService{

private auth_url = "/login/api/auth";

constructor(private http: Http){};

authenticate(username: String, pass: String): Promise<any>{
return this.http.post(this.auth_url, {username: username,pass: pass})
.then(response => response.json())

private handleError(error: any): Promise<any>{

return Promise.reject(error.message || error);


submitError is class level property, why its not accessible or undefined.
what is the proper way to access it?

Answer Source

You're facing a common problem in JavaScript.

Fortunately, in ES6 and TypeScript you can use an arrow function (lambda expression) to lexically capture the meaning of this.

}).catch((err:any) => {
    this.submitError = true; // this works

}).catch(function (err:any) {
        this.submitError = true; // this doesn't work

More information about arrow functions: Arrow Functions

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download