Javascript 有很多订阅者

Javascript 有很多订阅者,javascript,angularjs,typescript,angular,Javascript,Angularjs,Typescript,Angular,我在Angular 2中有一个页面和一个服务 当我调用服务函数this.Auth.login()时,它发出一个http post请求。我的问题是,只要请求返回数据,我就想在服务和页面中处理这些数据 我尝试了各种各样的东西,但不知道怎么做 我知道我的代码不能这样工作,因为现在this.Auth.login()返回订户对象。如果删除服务中的“.subscribe()”,它将在页面中工作。但那不是我需要的 我也试着回报一个承诺,但也无法让它起作用 有人知道我如何实现将来自http.post的数据同时保

我在Angular 2中有一个页面和一个服务

当我调用服务函数this.Auth.login()时,它发出一个http post请求。我的问题是,只要请求返回数据,我就想在服务和页面中处理这些数据

我尝试了各种各样的东西,但不知道怎么做

我知道我的代码不能这样工作,因为现在
this.Auth.login()
返回订户对象。如果删除服务中的“.subscribe()”,它将在页面中工作。但那不是我需要的

我也试着回报一个承诺,但也无法让它起作用

有人知道我如何实现将来自http.post的数据同时保存在两个控制器中,并在请求完成后立即使用它吗


这是我的密码

第页:

服务:

import {Http, Headers} from 'angular2/http';
import {Injectable} from 'angular2/core';

@Injectable()
export class AuthService {
    private http;

    constructor(http:Http) {
        this.http = http;
    }

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

        // maybe i need to return this as a promise
        return this.http.post('http://localhost:9000/auth/local', JSON.stringify({
                    email: email,
                    password: password
                }), {
                    headers: headers
                })
                .subscribe(data => {
                    do some stuff here too with the data
                ));
                // i tried to add .toPromise() but that didn't work
    }
}

我遗漏了其他代码行,因此可能缺少一些依赖项。不过一切都很好。

您可以在
服务的主体中使用
map
。i、 e

.map(data => {
                do some stuff here too with the data
                // still bubble up
                return data;
            ));

好吧,我不知道这是否合法,但它似乎对我有用:

var res = this.http.post('http://localhost:9000/auth/local', JSON.stringify({
        email: email,
        password: password
    }), {
        headers: headers
    });

res.subscribe(
    data => {
        console.log('data');
    },
    err => {
        console.log('err');
    },
    () => {  
        console.log('next');
    }
);

return res;

我试过了,得到了错误
this.http.post(…).map不是函数
;在AuthServiceMap中,除非有其他调用
subscribe()
(本例中显示的服务),否则不会执行
map
回调是否正确?如果是这样,那么这是需要注意的,如果您依赖于对数据执行某些操作,而不管调用代码是否调用observable上的
subscribe()
。ok
import'rxjs/add/operator/map'
起作用,但是map中的代码似乎不会执行,即使
subscribe()
在页面中被调用。
.map()
应该可以工作(即@basarat的答案)。这是一个正在工作的plunker:
var res = this.http.post('http://localhost:9000/auth/local', JSON.stringify({
        email: email,
        password: password
    }), {
        headers: headers
    });

res.subscribe(
    data => {
        console.log('data');
    },
    err => {
        console.log('err');
    },
    () => {  
        console.log('next');
    }
);

return res;