【问题标题】:Angular 2 / 4 toPromise works but I am having trouble with ObservablesAngular 2 / 4 toPromise 有效,但我在使用 Observables 时遇到问题
【发布时间】:2017-08-04 18:39:52
【问题描述】:

我正在尝试围绕 Observables 进行思考

这是我目前使用.toPromise 的方法

request.ts

get(url): Promise<any>
{
    //  HARD CODED A URL I FOUND , NOT USING THE "url" param
    return this.http.get("https://conduit.productionready.io/api/profiles/eric").map(response => {
        return response.json() || {success: false, message: "No response from server"};
    }).catch((error: Response | any) => {
        return Observable.throw(error.json());
    }).toPromise();
}

这行得通,

调用

event.service.ts

功能...

this.Request.get("/user").then(response => {
        console.log("Got response:", response);
    }).catch(error => {
        console.log("Got error:", error);
    }).then(response => {
        console.log("Another response:", response);
    }).catch(error => {
        console.log("Got another error:", error);
    });

相反,我想做的是 Observables

所以

我尝试“订阅”

订阅者

我不太明白如何使用“数据”和“订阅”等。

 var url = "https://conduit.productionready.io/api/profiles/eric";
    var blah;
    this.getDataObservable(url).subscribe(
         data => {
             blah = data;
             console.log("I CANT SEE DATA HERE: ", blah);
         }
     );

调用函数

getDataObservable(url: string) {
    return this.http.get(url)
        .map(data => {
            data.json();
            // the console.log(...) line prevents your code from working 
            // either remove it or add the line below (return ...)
            console.log("I CAN SEE DATA HERE: ", data.json());
            return data.json();
        });
}

【问题讨论】:

  • 无需添加return data.json()
  • 问题是我不明白这个,你能写一个答案给我看吗?
  • 确实需要返回data.json(),或其他任何事情。 map 只是一个生命周期钩子,您可以使用它来修改流中的值,然后再将其发送给订阅者。看看my answer here,以更好地了解 RxJS 的工作原理。
  • 你对代码做了什么,看起来有人审查了它并留下了他/她的 cmets。
  • 正确,我把它拿起来尝试使用它......

标签: javascript angular typescript observable


【解决方案1】:

很多个例子来说明如何做到这一点......这里有一个:

服务

getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

private handleError(error: Response) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

组件

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}

注意:这是使用原始的 Http 服务,而不是新的 HttpClient 服务。

要理解这段代码,你需要理解 Observables 和 Http 是如何工作的。我强烈建议阅读 Angular.io 上的文档,完成 angular.io 上的教程,或观看诸如此类的课程:https://app.pluralsight.com/library/courses/angular-2-getting-started(您可以注册免费一周观看。)

【讨论】:

  • 嗨 Deb,去年 9 月完整发布之前,我正在观看你在复数视觉上的 angular 2 视频,我打算改用你更新的视频,但我正在和库珀一起学习另一个复数视觉课程/eames "fundamentals" 我确实有点向前跳了...... Observables 看起来非常棒 - 我需要玩这个并尝试将我的头包裹在它周围 thx Deb
  • 酷! Retrieving Data Using Http 模块涵盖了 Observables 和 Http 服务。这详细解释了这段代码。请务必观看更新的课程。我在 10 月份为 Angular 的发布版本做了一个新版本。
【解决方案2】:

你的服务应该是这样的,所以你可以在组件中订阅

getDataObservable(url: string) {
    return this.http.get(url).map(data =>  data.json()).catch(error=>Observable.throw(error));
}

【讨论】:

  • ERROR TypeError: data.json(...).catch is not a function
  • @JeremyMiller 抱歉错过了 data.json() 旁边的括号。更正了上面的代码
  • 如何在 .map 中输出 console.log ... 显示数据或 data.json - 我一直在尝试 ...
  • 这不起作用.map(data =&gt; { data.json(); console.log('test', data.json) })
  • @JeremyMiller 是的
猜你喜欢
  • 2016-11-07
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2017-02-01
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多