【问题标题】:Angular2 rest calls in backgroundAngular2在后台休息调用
【发布时间】:2016-08-24 06:58:54
【问题描述】:

我刚刚按照 jhon papa 的示例创建了示例应用程序。(快速启动程序)。 我设计了服务类来从我的休息服务中获取 json 数据 http://localhost:8081//Myserver/rest/heros

import { Injectable } from '@angular/core';
import { Http, Response , Headers} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
import { Code } from './code';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
    constructor(private http: Http) { }
           private heroesUrl = 'http://localhost:8081//Myserver/rest/heros';  // URL to web api


    getHeroes() {
        return this.http.get(this.heroesUrl)
            .toPromise()
            .then(
            response => response.json() as Hero[])
            .catch(this.handleError);
    }
    getHero(id: number) {
        return this.getHeroes()
            .then(heroes => heroes.find(hero => hero.id === id));
    }

    private handleError(error: any) {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

服务类工作正常,英雄也列在 UI 中(忘记这里的 CROS 起源问题)。但是我在这里注意到一件事,其余对 http://localhost:8081//Myserver/rest/heros 的调用是直接从浏览器发送的(我可以在开发工具的网络选项卡中看到它)。

根据我的应用程序,它不应该从浏览器发送,而是应该像 JSF 中的后端 bean 类一样进行处理,然后将数据提供给相关的组件。我相信这也将解决我的 CROS 起源问题。 Dose Angular2 有这样的选择吗?请提出正确的实现方法。

【问题讨论】:

    标签: node.js angular


    【解决方案1】:

    您可以使用 WebWorkers 将代码执行移出主 UI 线程。 Angular2 对此提供了直接支持(实验性)。

    我怀疑这会改变关于 CORS 的任何事情。 为了使 CORS 正常工作,您的服务器需要使用正确的 CORS 标头进行响应。

    另见http://www.syntaxsuccess.com/viewarticle/web-workers-in-angular-2.0

    【讨论】:

    • - 感谢您的快速回复,请澄清我的问题。
    • - WebWorker 也会处理所有其他组件吗?
    • 我没有做太多,但 AFAIK UI 线程只运行渲染,所有其他代码都在 WebWorker 中运行。绑定数据和事件在 UI 线程和 WebWorker 线程之间传递(一切都完全透明)。
    • - 我们需要为每个方法单独注册吗?
    • 您只需要引导您的应用程序两次,一次用于 WebWorker,一次用于 UI 线程。否则,只要您按照 Angular2 指南工作,您就不需要做太多事情(不直接访问 DOM - 这仍然可以完成,但需要额外的工作)。
    猜你喜欢
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2015-04-15
    • 2017-08-24
    • 2012-05-10
    • 2013-01-31
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多