【问题标题】:Calling web API from a service in Angular 2从 Angular 2 中的服务调用 Web API
【发布时间】:2016-04-12 18:43:04
【问题描述】:

我正在使用 Angular 2.0 测试版。我需要从服务调用 Web API。但我没有得到任何解决方案。

mobileService.ts

import {Http, Headers, HTTP_PROVIDERS} from 'angular2/http';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import { Mobile } from './datatypes/Mobile';

@Injectable()
export class MobileService {          
     constructor(public http: Http) {     
        this.http = http;
        }

getMobiles() {        
    // return an observable
    return this.http.get("api/ElectronicsAPI/Get")
        .map((responseData) => {
            return responseData.json();
        })
        .map((mobiles: Array<any>) => {
            let result: Array<Mobile> = [];
            if (mobiles) {
                mobiles.forEach((mobile) => {
                    result.push(
                        new Mobile(mobile.name,
                            mobile.price));
                });
            }
            return result;
        });
}
}

错误是,

  • this.http.get(...).map 不是函数

我也有一些与此主题相关的问题。在那,他们提到要导入map

  • 导入 'Rxjs/add/operator/map'

但是如何在 TypeScript 中做到这一点?

还有其他方法可以为地图功能导入插件吗?

boot.ts

import {bootstrap}    from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {AppComponent} from './app.component';
import {HTTP_PROVIDERS} from 'angular2/http';

bootstrap(AppComponent,[ROUTER_PROVIDERS,HTTP_PROVIDERS]);

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以在 mobileService.ts 文件中使用以下内容:

    import 'Rxjs/add/operator/map'
    

    这个导入应该在你使用map方法的地方完成。

    以下答案也可以帮助您:

    希望对你有帮助 蒂埃里

    【讨论】:

    • 感谢您的回复...但是,我对这个导入声明有一些疑问...它将如何映射?我应该在 index.html 中包含任何脚本文件吗?
    • 事实上,您应该使用script 元素将Rx.js 包含在您的index.html 文件中。导入必须在mobileService.ts 文件中完成...
    • 现在我得到了解决方案。在 system.config 中进行一些更改后
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2018-03-08
    相关资源
    最近更新 更多