8

Http对于 JWT 身份验证,我现在使用与 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,你有没有更好的方法来实现它?

4

2 回答 2

9

为什么要订阅in sharedService,什么时候可以使用这种方法!

@Injectable()
export class Auth {
    constructor(public http: Http) {}

    public authentificate(credentials: CredentialsModel) {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');

            return  this.http.post(config.LOGIN_URL, JSON.stringify(credentials), {headers})      //added return
            .map(res => res.json());
            //.subscribe(
            //    data => this._saveJwt(data.id_token),
            //    err => console.log(err)
            //);
    }
}

@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).subscribe(
               (data) => {this.auth._saveJwt(data.id_token)},  //changed
               (err)=>console.log(err),
               ()=>console.log("Done")
            );
    }
}



如果您想订阅,请继续编辑sharedServicecomponent您肯定可以采用这种方法。但我不推荐这个,而是在编辑部分对我来说很完美之前。

我无法用你的代码测试它。但看看我的例子here(tested)。单击myFriends tab,检查浏览器控制台和 UI。浏览器控制台显示订阅结果sharedService& UI 显示订阅结果component.


  @Injectable()
  export class Auth {
    constructor(public http: Http) {}

    public authentificate(credentials: CredentialsModel) {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');

           var sub =  this.http.post(config.LOGIN_URL, JSON.stringify(credentials), {headers})      //added return
            .map(res => res.json());

           sub.subscribe(
                data => this._saveJwt(data.id_token),
                err => console.log(err)
               );

           return sub;
    }
}

export class LoginComponent {
    private cred: CredentialsModel = new CredentialsModel();

    constructor(public auth: Auth) {}

    submitForm(e: MouseEvent) {
        e.preventDefault();
        this.auth.authentificate(this.cred).subscribe(
               (data) => {this.auth._saveJwt(data.id_token)},  //not necessary to call _saveJwt from here now.
               (err)=>console.log(err),
               ()=>console.log("Done")
            );
    }
}
于 2016-03-09T10:29:45.877 回答
2

只能订阅服务中的事件并返回对应的 observable:

public authentificate(credentials: CredentialsModel) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    var obs = this.http.post(config.LOGIN_URL, JSON.stringify(credentials), {headers})
        .map(res => res.json())
        .subscribe(
            data => this._saveJwt(data.id_token)
        );

    return obs;
}

如果发生错误,您可以使用catch运算符捕获它:

submitForm(e: MouseEvent) {
  e.preventDefault();
  this.auth.authentificate(this.cred).catch((err) => {
    console.log('ERROR component', err);
  });
}

编辑

share如果你想订阅一个 observable 两次,你需要通过调用该方法使其“热” 。

您还可以利用do运算符并仅订阅组件:

public authentificate(credentials: CredentialsModel) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.post(config.LOGIN_URL, JSON.stringify(credentials), {headers})
        .map(res => res.json())
        .do(
            data => this._saveJwt(data.id_token)
        );
}
于 2016-03-09T10:14:52.420 回答