我想知道,在处理响应(保存令牌)后,如何通过使用新的HttpClient(来自@ angular / common / http的角度为4.3+)轻松地通知组件有关http响应(成功或错误)的信息。服务。
早些时候,我正在使用此代码(使用@ angular / http):
login(username: string, password: string): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let url = this.apiAddr + '/login';
var body = 'username=' + username + '&password=' + password;
return this.http.post(url, body, options).map((res) => {
let body = res.json();
this.jwtoken = body.token;
this.username = username;
this.saveToken();
return "Login successful!";
})
.catch(this.handleError);
}
通过使用新模块,我不确定如何返回Observable并同时从服务访问它。这就是我现在所拥有的(auth.service.ts):
login(username: string, password: string) {
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const url = apiAddr + '/login';
const body = 'username=' + username + '&password=' + password;
const options = {
headers: headers,
};
this.http.post<LoginResponse>(url, body, options).subscribe(
data => {
this.jwtoken = data.token;
this.username = username;
this.lastTokenRefreshAt = new Date();
this.saveUserToken();
}, err => {
console.log('Error occured');
console.log(err);
});
}
此后,我想通知LoginComponent,我可以在哪里导航到另一个页面。
答案 0 :(得分:2)
当组件像这样调用它时,使用observable的do运算符来访问服务的响应:
import 'rxjs/add/operator/do';
login(username: string, password: string) {
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const url = apiAddr + '/login';
const body = 'username=' + username + '&password=' + password;
const options = {
headers: headers,
};
return this.http.post<LoginResponse>(url, body, options).do(
data => {
this.jwtoken = data.token;
this.username = username;
this.lastTokenRefreshAt = new Date();
this.saveUserToken();
});
}
您可以捕获调用login的组件中的错误。
答案 1 :(得分:1)
在更新到angular 6并使用新版本的RxJs之后,我不得不更改do方法,因为该方法已被重命名/弃用。为了获得类似Sonicd300答案的结果,我必须对管道使用tap方法:
import { tap } from 'rxjs/operators';
login(username: string, password: string) {
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const url = this.apiAddr + '/login';
const body = 'username=' + username + '&password=' + password;
const options = {
headers: headers,
};
return this.http.post<LoginResponse>(url, body, options).pipe(
tap(
data => {
this.jwtoken = data.token;
this.username = username;
this.lastTokenRefreshAt = new Date();
this.saveUserToken();
return 'Login successful';
})
);
}