使用Angular 2与HTTP REST API交互

32

所以,我正在跟随Angular 2官网上的TypeScript指南,并且在http API集成方面遇到了困难。我正在尝试创建一个简单的应用程序,可以通过SoundCloud API搜索歌曲,但我很难实现并理解如何开始,并且在线资源使用了许多不同的方法(我认为是由于过去Angular 2语法的快速更改导致的)。

所以目前我的项目看起来像这样:

app
  components
    home
      home.component.ts
      ...
    search
      search.component.ts
      ...
    app.ts
    ...
  services
    soundcloud.ts
  bootstrap.ts
index.html

这个例子中没有花哨的东西,主要文件为

app.ts

import {Component, View} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';

import {HomeComponent} from './home/home.component';
import {SearchComponent} from './search/search.component';

@Component({
    selector: 'app',
    templateUrl: 'app/components/app.html',
    directives: [ROUTER_DIRECTIVES]
})

@RouteConfig([
  {path: '/home', name: 'Home', component: HomeComponent, useAsDefault: true},
  {path: '/search', name: 'Search', component: SearchComponent}
])

export class App { }

bootstrap.ts

    import {App}     from './components/app';
import {bootstrap}        from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';

bootstrap(App, [
  ROUTER_PROVIDERS
]);

我一直在尝试弄清楚soundcloud.ts,但是我无法做到,并且下面的方法存在错误。 即@Inject未找到(我认为我在这里使用过时的语法)。 基本上我想在我的应用程序中使用soundcloud服务进行api调用,从搜索组件中进行。

import {Injectable} from 'angular2/core'
import {Http} from 'angular2/http'

@Injectable()
export class SoundcloudService {
 http : Http

 constructor(@Inject(Http) http) {
   this.http = http;
 }
}

由于我还没有掌握基础知识,因此此处未包括SoundCloud API。


1
在您的引导文件中添加HTTP_PROVIDERS,并确保您已添加了http.dev.js库,然后将@Inject(Http) http更改为http: Http - Langley
1
你遇到的错误是因为你导入了 @Injectable 但没有导入 @Inject,并且你同时使用了两者。 - Langley
@Langley,您能否详细说明一下您的评论?需要在index.html中添加http.dev.js作为脚本吗?我不确定我需要如何更改第二部分。 - Ilja
1
将它们作为答案添加,这样更易读。 - Langley
如果您感兴趣,这里有一篇关于Http的文章:http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http - TGH
2个回答

36

@langley提供了一个不错的答案,但是我想补充一些内容,所以把它作为一个答案发布。

首先,为了使用Rest API,我们需要导入HttpHTTP_PROVIDERS模块。由于我们正在谈论Http,因此很明显的第一步是:

<script src="node_modules/angular2/bundles/http.dev.js"></script>

但是,在引导文件中提供HTTP_PROVIDERS是一个好的实践,因为这样提供的服务可以在全局范围内使用,并且可以在整个项目中使用。

bootstrap(App, [
    HTTP_PROVIDERS, some_more_dependencies
]);

需要包含的导入内容为....

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';

有时在使用API发送access_token等内容时,我们需要提供Headers,方法如下:

this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))

现在关于 RequestMethods: 基本上我们使用GET,POST但还有一些其他选项你可以参考这里...

我们可以使用请求方法 RequestMethod.method_name

API中还有一些其他选项,但目前我已经发布了一个示例用于POST请求,通过使用一些重要的方法,它将帮助您:

PostRequest(url,data) {
        this.headers = new Headers();
        this.headers.append("Content-Type", 'application/json');
        this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    return [{ status: res.status, json: res.json() }]
                }
            });
    }

如果需要更多信息,您也可以在这里参考

另请参阅 -

更新

导入方式已更改为

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from '@angular/http';

'data' 未定义。 - Sebastian Olsen
@SebastianOlsen data是从组件传递到服务的参数。 - Pardeep Jain
我是个傻瓜,我没意识到这是一个POST请求。它完美地工作了,谢谢! - Sebastian Olsen
呵呵...没关系 :p - Pardeep Jain
2
警告,自Angular 5起,来自@angular/httpHttp服务已被弃用。您应该使用来自@angular/common/httpHttpClient代替。 - Bastien

7

您需要在index.html文件中添加以下行:

<script src="node_modules/angular2/bundles/http.dev.js"></script>

您需要添加HTTP_PROVIDERS

bootstrap(App, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS
]);

在您的boot.ts/bootstrap.ts文件中引入它们,并进行相应的导入。

您需要在DojoService类文件中导入@Inject

import {Injectable, Inject} from 'angular2/core'

就像您导入了 @Injectable 一样。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接