【问题标题】:Using http rest apis with angular 2使用 angular 2 的 http rest api
【发布时间】:2023-03-25 06:00:01
【问题描述】:

所以,我正在通过 typescript 在他们的网站上关注 angular 2 指南,并被困在 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 未包含在此处,因为我无法先了解基础知识。

【问题讨论】:

  • 在启动文件中添加 HTTP_PROVIDERS 并确保添加了 http.dev.js 库并将@Inject(Http) http 更改为http:Http
  • 你得到的错误是因为你正在导入 @Injectable 而不是 @Inject 并且你正在使用两者
  • @Langley 你能扩展你的评论吗? http.dev.js 需要添加为 index.html 中的脚本吗?我不确定我需要如何更改第二部分。
  • 将它们添加为答案,这样更具可读性。
  • 这里有一篇关于Http的文章如果你有兴趣syntaxsuccess.com/viewarticle/angular-2.0-and-http

标签: javascript angular http


【解决方案1】:

@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';

有时我们需要提供Headers,同时使用API​​ 来发送access_token 以及通过这种方式完成的更多事情:

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

现在到 RequestMethods:基本上我们使用 GET、POST 但您可以使用更多选项refer here...

我们可以使用 requestmethods 作为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() }]
                }
            });
    }

您也可以refer here 了解更多信息。

另见-

更新

导入已更改为

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

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

【讨论】:

  • 'data' 未定义。
  • @SebastianOlsen data 是从组件传递到服务的参数。
  • 我是个白痴,我没有意识到这是一个 POST 请求。完美运行,谢谢!
  • 呵呵...没关系:p
  • 警告,自 Angular 5 以来,@angular/httpHttp 服务已被弃用。您应该使用来自@angular/common/http insteed 的HttpClient
【解决方案2】:

你需要添加这一行:

&lt;script src="node_modules/angular2/bundles/http.dev.js"&gt;&lt;/script&gt;

在您的 index.html 文件中。

您需要添加HTTP_PROVIDERS:

bootstrap(App, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS
]);

在您的 boot.ts/bootstrap.ts 文件中,当然也可以导入它们。

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

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

就像你导入了@Injectable

【讨论】:

    猜你喜欢
    • 2017-03-21
    • 2017-04-09
    • 1970-01-01
    • 2015-10-19
    • 2016-01-31
    • 1970-01-01
    • 2023-04-04
    • 2018-06-18
    • 1970-01-01
    相关资源
    最近更新 更多