提供 responce.json () 对于我的情况不起作用
组件.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 这样的错误
请帮助我
尝试使用这种结构:
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) {
}
这对我来说很有效
在您的服务页面
//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']);
}
});
它对我来说非常有效
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');