Angular 2 中使用 subscribe 调用成功、错误回调

问题描述 投票:0回答:3

它给出 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);
}

给予[物体,物体]

如果我使用地图功能服务,例如 .map(response => response.json()),它会给出类似 responce.json () is not function 的错误。

angular angular2-template angular2-services
3个回答
20
投票

尝试使用这种结构:

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) {
}

这对我来说很有效


2
投票

在您的服务页面

//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']);
    }
});

它对我来说非常有效


0
投票

如在RxJS网站上看到的

import { Observable } from 'rxjs';

const observable = new Observable((subscriber) => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  setTimeout(() => {
    subscriber.next(4);
    subscriber.complete();
  }, 1000);
});

console.log('just before subscribe');
observable.subscribe({
  next(x) {
    console.log('got value ' + x);
  },
  error(err) {
    console.error('something wrong occurred: ' + err);
  },
  complete() {
    console.log('done');
  },
});
console.log('just after subscribe');
© www.soinside.com 2019 - 2024. All rights reserved.