Angular 2从RxJs订阅返回数据

时间:2016-03-31 20:08:33

标签: angular typescript asynchronous rxjs

我有一个带有身份验证功能的服务 -

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;
    }

因此,如果我调用authenticate函数console.log(authenticate('a', 'b'));,它会记录undefined,因为在订阅函数将数据放入其中之前返回ret变量。如何从authenticate函数返回http响应数据?我以前从未对RxJS进行过任何反应式编程,而这正是角度2似乎正在使用的。

PS。是否有适合javascript的CSP解决方案,如go channel或core.async?

2 个答案:

答案 0 :(得分:12)

我使用Observables和Observers来构建我的解决方案。由于@Injectable创建了一个单例类,我在其中声明了一个Observable,然后我将其暴露给我的组件。当我将任何数据放入其中时,所有订阅者都会收到有关该事件的通知。警告:如果你在zone.js 0.5中使用它,它将无法工作。适用于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 => {
                ...
            }
        )
    }
}

答案 1 :(得分:4)

您需要直接返回与您的请求相对应的observable:

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');

  return this.http.post('http://localhost:5000/api/authenticate/', packet, {
    headers: headers
  })
  .map(res => res.json());
}

authenticate方法的调用者必须在其上订阅才能收到结果:

this.service.authenticate('username', 'password').subscribe(
  (result) => {
    console.log('Result received');
    console.log(result);
  }
);