web-dev-qa-db-ja.com

Angle2でサブスクライブを使用して成功、エラーコールバックを呼び出しますか?

私の場合、responce.json()を指定しても機能しません

component.ts

 this.AuthService.loginAuth(this.data).subscribe(function(response) {
  console.log("Success Response" + response)
},
  function(error) {
  console.log("Error happened" + error)
},
  function() {
  console.log("the subscription is completed")
});

AuthService.ts

     loginAuth(data): Observable<any> {
  return this.request('POST', 'http://192.168.2.122/bapi/public/api/auth/login', data,{ headers:this. headers })
      .map(response => response)
      //...errors if any
      .catch(this.handleError);
  }

[object、objet]を与えると、.map(response => response.json())のようなマップ関数サービスを配置すると、responce.json()が関数ではないようなエラーが発生します。

私を助けてください

11
Runali

この構造を使用してみてください。

this.AuthService.loginAuth(this.data).subscribe(
        suc => {
            console.log(suc);
        },
        err => {
            console.log(err );
        }
    );

また、次のようなサーバーに送信されるデータを文字列化することもできます。

loginAuth(data) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    var info = JSON.stringify(data);

    return this._http.request("http://192.168.2.122/bapi/public/api/auth/login", info , { headers: headers }).map(res => res.json())
}

そして、次のようなHttpを参照するサービスのコンストラクターで変数を宣言する必要があります。

import { Http, Headers, Response, URLSearchParams } from '@angular/http';    
constructor(private _http: Http) {
}

これは私のために働いた方法です

18
Rossco

あなたのサービスページで

//Import if needed

import { Observable } from 'rxjs/Observable';    
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

let options = new RequestOptions({ headers: this.headers });
return this.http.post('http://192.168.2.122/bapi/public/api/auth/login', data, options)
.map((res: Response) => {
    return { "res": res.json() };
})
.catch((e: any) => {
    console.log(e.status);
    return Observable.throw({"Errors":e.json()});
});

テンプレートtsファイル

this.AuthService.loginAuth(this.data).subscribe((result: any) => {
    let res = result.res;
    console.log(res)
},(error: any) => {
    if(typeof error['Errors'] !="undefined"){
        console.log(error['Errors']);
    }
});

それは私のために完璧に働いています

1
bipin patel