RxJs订阅的Angular 2返回数据 [英] Angular 2 return data from RxJs subscribe

查看:205
本文介绍了RxJs订阅的Angular 2返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项具有身份验证功能的服务-

I've a service with an authenticate function -

authenticate(username: string, password: string) {
        let ret;
        let packet = JSON.stringify({
            username: username,
            password: password
        });

        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        this.http.post('http://localhost:5000/api/authenticate/', packet, {
            headers: headers
        })
        .map(res => res.json())
        .subscribe(
            data => { 
                // put return data into ret
                ret = data.token;
            },
            err => console.log(err),
            () => {
                // this works!
                console.log(ret);
            }
        );

        // get's returned before I put data into it
        return ret;
    }

因此,如果我调用身份验证功能console.log(authenticate('a', 'b'));,它将记录undefined,因为在订阅功能可以将数据放入其中之前,已返回ret变量.如何从authenticate函数返回http响应数据?我以前从未用RxJS进行过任何反应式编程,这就是angular 2似乎正在使用的方法.

So if I call the authenticate function console.log(authenticate('a', 'b'));, it logs undefined since the ret variable is returned before the subscribe function can put the data into it. How can I return the http response data from authenticate function? I've never done any reactive programming with RxJS before and that's what angular 2 seems to be using.

PS.有没有像Java一样不错的CSP解决方案,例如go频道或core.async?

PS. Is there any decent CSP solution for javascript like go channels or core.async?

推荐答案

我使用了Observables和Observers来构建我的解决方案.由于@Injectable创建了一个单例类,因此我在其中声明了一个Observable,然后将其公开给我的组件.当我将任何数据放入其中时,所有订阅者都会收到有关该事件的通知.警告:如果将它与zone.js 0.5一起使用,它将无法正常工作.适用于0.6.

I used Observables and Observers to build my solution. Since @Injectable creates a singleton class, I declared an Observable inside of it which I then exposed to my component. When I put any data into it, all subscribers get notified of the event. Warning: if you use this with zone.js 0.5, it won't work. Works with 0.6.

import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';


@Injectable()
export class AuthService {
    // expose to component
    notification$: Observable<Notification>;
    private observer: Observer<Notification>;

    ....

    constructor(private http: Http) {
        this.notification$ = new Observable(observer => this.observer = observer).share();
    }

    authenticate({username, password}) {
        let packet = JSON.stringify({
            username: username,
            password: password
        });

        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        this.http.post(`${this.baseUri}/authenticate/`, packet, {
            headers: headers
        })
        .map(res => res.json())
        .subscribe(
            data => {
                if (data.success && data.token) {
                    this.saveJwt(data.token);
                } else {
                    this.deleteJwt();
                }
                // put data into observavle 
                this.observer.next({
                    message: data.message,
                    type: data.success
                });
            },
            err => {
                // put data into observavle  
                this.observer.next({
                    message: 'Error connecting to server',
                    type: false
                })
            },
            () => {}
        );
    }
}


export class AuthComponent implements OnInit {
    observable: Observable<Notification>;

    ...

    ngOnInit() {
        // subscribe to the observable
        this.observable = this.authService.notification$;
        this.observable.subscribe(
            data => {
                ...
            }
        )
    }
}

这篇关于RxJs订阅的Angular 2返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆