【发布时间】:2026-02-10 13:15:01
【问题描述】:
对于 JWT 身份验证,我现在使用新的 Http 模块与 Observables 一起发出请求以获取令牌。
我有一个简单的Login 组件显示表单:
@Component({
selector: 'my-login',
template: `<form (submit)="submitForm($event)">
<input [(ngModel)]="cred.username" type="text" required autofocus>
<input [(ngModel)]="cred.password" type="password" required>
<button type="submit">Connexion</button>
</form>`
})
export class LoginComponent {
private cred: CredentialsModel = new CredentialsModel();
constructor(public auth: Auth) {}
submitForm(e: MouseEvent) {
e.preventDefault();
this.auth.authentificate(this.cred);
}
}
我有一个 Auth 服务发出请求:
@Injectable()
export class Auth {
constructor(public http: Http) {}
public authentificate(credentials: CredentialsModel) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(config.LOGIN_URL, JSON.stringify(credentials), {headers})
.map(res => res.json())
.subscribe(
data => this._saveJwt(data.id_token),
err => console.log(err)
);
}
}
效果很好,但现在我想在我的组件中显示错误消息,所以我需要在 2 个地方订阅(Auth 用于管理成功,Login 用于管理错误)。
我使用share 运算符实现了它:
public authentificate(credentials: CredentialsModel) : Observable<Response> {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const auth$ = this.http.post(config.LOGIN_URL, JSON.stringify(credentials), {headers})
.map(res => res.json()).share();
auth$.subscribe(data => this._saveJwt(data.id_token), () => {});
return auth$;
}
在组件内部:
submitForm(e: MouseEvent) {
e.preventDefault();
this.auth.authentificate(this.cred).subscribe(() => {}, (err) => {
console.log('ERROR component', err);
});
}
它有效,但我觉得做错了..
我只是将我们使用 angular1 和 promises 的方式进行转换,您有没有更好的方法来实现它?
【问题讨论】:
-
您在
authService的其他任何地方使用auth$吗?如果没有那么你不需要订阅autheService...
标签: angular observable rxjs5 angular2-http