使用带有 angular 2 的 http rest apis [英] Using http rest apis with angular 2

查看:23
本文介绍了使用带有 angular 2 的 http rest apis的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在通过打字稿在他们的网站上关注 angular 2 指南,并坚持使用 http api 集成.我正在尝试制作一个可以通过 soundcloud api 搜索歌曲的简单应用程序,但是我很难实现和理解如何开始,并且在线资源以多种不同的方式进行(我相信可以快速更改 angular 2 语法回到当天).

所以目前我的项目是这样的

应用成分家主页.component.ts...搜索search.component.ts...应用程序...服务soundcloud.tsbootstrap.ts索引.html

示例中没有什么特别的,主要文件是

app.ts

import {Component, View} from 'angular2/core';从 'angular2/router' 导入 {RouteConfig, ROUTER_DIRECTIVES};从 './home/home.component' 导入 {HomeComponent};从 './search/search.component' 导入 {SearchComponent};@成分({选择器:'应用',templateUrl: 'app/components/app.html',指令:[ROUTER_DIRECIVES]})@RouteConfig([{path: '/home', name: 'Home', 组件: HomeComponent, useAsDefault: true},{路径:'/search',名称:'搜索',组件:SearchComponent}])导出类 App { }

bootstrap.ts

 import {App} from './components/app';从 'angular2/platform/browser' 导入 {bootstrap};从'angular2/router'导入{ROUTER_PROVIDERS};引导程序(应用程序,[ROUTER_PROVIDERS]);

并且我试图找出 soundcloud.ts 但是我无法并且在以下方法中存在错误,即未找到 @Inject(我假设我是在这里使用过时的语法).本质上,我想在我的应用程序表单搜索组件中使用 soundcloud 服务进行 api 调用.

从'angular2/core'导入{Injectable}从 'angular2/http' 导入 {Http}@Injectable()导出类 SoundcloudService {http : Http构造函数(@Inject(Http)http){this.http = http;}}

此处未包含 soundcloud api,因为我无法先了解基础知识.

解决方案

@langley 提供的答案很好,但我想添加更多要点,因此发布作为答案.

首先,为了使用 Rest API,我们需要导入 HttpHTTP_PROVIDERS 模块.当我们谈论 Http 时,第一步显然是.

<块引用>

但是,在引导文件中提供 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 但还有更多选项您可以 参考这里...

我们可以使用 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({方法:RequestMethod.Post,网址:网址,标头:this.headers,正文:JSON.stringify(数据)})返回 this.http.request(new Request(this.requestoptions)).map((res: 响应) => {如果(资源){返回 [{ 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';

So, I am following angular 2 guides on their website via typescript and am stuck at http api integration. I'm trying to make a simple application that can search via soundcloud api for a song, however I have difficulties implementing and understanding how to get going and online resources do it in so many different ways (I believe do to rapid angular 2 syntax changes back in the day).

So at the moment my project looks like this

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

Nothing fancy going on in the example, main files would be

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
]);

And I was trying to figure out soundcloud.ts however am not able to and there are errors in following approach i.e. @Inject is not found (I assume I am using outdated syntax here). Essentially I would like to use soundcloud service for api calls within my app form search component.

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 not included here as I can't get basics down first.

解决方案

Well good answer provided by @langley but I would like to add some more points so posting as an answer.

First of all for consuming Rest APIs we need the Http and HTTP_PROVIDERS modules to be imported. As we are talking about Http the very first step is obviously.

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

But yes it is a good practice to provide HTTP_PROVIDERS in the bootstrap file because by using this way it is provided on a global level and is available to the whole project like this.

bootstrap(App, [
    HTTP_PROVIDERS, some_more_dependencies
]);

and the imports to be included are....

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

Sometimes we need to provide Headers while consuming API's for sending access_token and many more things which is done this way:

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

Now to RequestMethods: bascially we use GET, POST but there are some more options you can refer here...

We can use requestmethods as RequestMethod.method_name

There are some more options for the APIs but for now I have posted one example for POST request which will help you by using some important methods:

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() }]
                }
            });
    }

you can refer here too for more info.

see also -

Update

import has been changed from

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

to

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

这篇关于使用带有 angular 2 的 http rest apis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆