Angular2:如何正确地订阅服务和组件中的Http.post observable?

ber*_*ndg 6 observable angular2-http rxjs5 angular

对于JWT身份验证,我现在发出一个post请求,以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个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)
            );
    }
}
Run Code Online (Sandbox Code Playgroud)

运行良好但现在我想在我的组件中显示错误消息,所以我需要在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$;
}
Run Code Online (Sandbox Code Playgroud)

在组件内部:

submitForm(e: MouseEvent) {
    e.preventDefault();
    this.auth.authentificate(this.cred).subscribe(() => {}, (err) => {
        console.log('ERROR component', err);
    });
}
Run Code Online (Sandbox Code Playgroud)

它有效,但我觉得做错了.我只是用angular1转换我们做的方式promises,你看到更好的方法来实现吗?

mic*_*yks 7

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)
            //);
    }
}
Run Code Online (Sandbox Code Playgroud)
@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")
            );
    }
}
Run Code Online (Sandbox Code Playgroud)



如果您想订阅sharedService,component编辑,您肯定可以采用这种方法.但是在编辑部分之前我不推荐这个,对我来说似乎很完美.

我无法用你的代码测试它.但看看我的例子(测试).单击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;
    }
}
Run Code Online (Sandbox Code Playgroud)
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")
            );
    }
}
Run Code Online (Sandbox Code Playgroud)