2016-10-18 11 views
1

私は角と形容詞が新です。私は、エラー "未処理の約束拒絶TypeError例外を:プロパティを設定できません" そうだ、ここ角度2処理されていない約束の拒否TypeError

を私のコードは次のとおりです。

login.component.ts

export class LoginComponent implements OnInit { 

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


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

onSubmit(){ 

    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; 

    } 
    else{ 
     // do something 
    } 

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

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



    }); 




} 

ログイン-service.ts

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

import 'rxjs/add/operator/toPromise'; 

@Injectable() 
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}) 
         .toPromise() 
         .then(response => response.json()) 
         .catch(this.handleError); 
} 

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

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

} 

submitErrorはクラスレベルのプロパティーで、アクセスできない、または未定義の理由です。 これにアクセスする適切な方法は何ですか?

答えて

3

login.component.tsでは、JavaScriptでの共通の問題に直面しています。

幸いにも、ES6とTypeScriptでは、矢印関数(ラムダ式)を使用して、thisの意味を字句で取り込むことができます。矢印の機能について

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

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

詳細情報:どういたしまして@Jawad Arrow Functions

+0

がご支援 – Jawad

+0

をありがとう、私はあなたを助けることができたうれしいです。私はあなたが私の答えを受け入れているのを見ましたが、あなたも投票してください(回答の左側にある数字の上の上矢印(今は0)をクリックしてください)? – Alon

1

に変更し、それを:

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

httpServiceを使用するための良い方法は、あなたがhttpServiceを呼び出し、jsonデータを返すときで、その後、あなたはそれがresponseまたはerrorであるとして、このデータを処理する必要が..あなたが必要ですデータにはsubscribeとなります。

this.loginService.authenticate(this.model.login_id, this.model.password) 
.subscribe((response) => { 

    if(response.status == 404){ 

     this.submitError = true; 

    } 
    else{ 
     // do something 
    } 

    }, 
    error => { 
      console.log(error); 
      this.submitError = true; 
    }); 
関連する問題