使用HTTP REST API的具有角2 [英] Using http rest apis with angular 2

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

问题描述

所以,我下面通过打字稿在其网站上的角2导游和我停留在HTTP API集成。我试图做一个简单的应用程序,可以通过API的SoundCloud搜索一首歌曲,但是我有苦衷实施和了解如何获得持续和在线资源做它在很多不同的方式(我相信做快速角2语法变化在当天返回)。

所以此刻我的项目看起来像这样

 应用
  组件
    家
      home.component.ts
      ...
    搜索
      sea​​rch.component.ts
      ...
    app.ts
    ...
  服务
    soundcloud.ts
  bootstrap.ts
的index.html

没什么特别的例子回事,主要文件将是

app.ts

 进口{组件,查看}从'angular2 /核心;
进口{RouteConfig,ROUTER_DIRECTIVES}从'angular2 /路由器;从./home/home.component进口{HomeComponent};
进口{}的SearchComponent从'./search/search.component';@零件({
    选择:应用程序,
    templateUrl:应用程序/组件/ app.html',
    指令:[ROUTER_DIRECTIVES]
})@RouteConfig([
  {路径:'/家,名称:'家',组成:HomeComponent,useAsDefault:真正},
  {路径:'/搜索,名称:'搜索',成分:SearchComponent的}
])出口类应用{}

bootstrap.ts

 进口{}应用程序从./components/app';
从angular2 /平台/浏览器的进口{}引导;
从angular2 /路由器的进口{ROUTER_PROVIDERS};引导程序(App [
  ROUTER_PROVIDERS
]);

和我想弄清楚的 soundcloud.ts 但是我不能够,有在下面的方法错误,即 @Inject 不是发现(我想我在这里使用过时的语法)。基本上我想用的SoundCloud的服务,为我的应用程序形式的搜索组件中的API调用。

 进口{}注射从'angular2 /核心
进口{}的Http从'angular2 / HTTP@Injectable()
出口类SoundcloudService {
 HTTP是:http 构造函数(@注入(HTTP)HTTP){
   this.http = HTTP;
 }
}

这里不包括的SoundCloud API作为我不能得到基本的先坐下。


解决方案

由@langley提供很好很好的答案,但我想补充一些更多的积分,以便张贴作为答案。

首先为consuminng REST API的,我们需要 HTTP HTTP_PROVIDERS 模块导入。
如果我们谈论的Http第一步是显而易见的。

 <脚本SRC =node_modules / angular2 /包/ http.dev.js>< / SCRIPT>


  

不过是的,它是一个很好的做法,因为通过这种方式,它提供了在全球层次上,可供类似以下整个项目提供 HTTP_PROVIDERS 中的引导文件。


 引导程序(App [
    HTTP_PROVIDERS,some_more_dependency的
]);

和进口的....

 进口{HTTP,响应,RequestOptions,头,请求,RequestMethod}从'angular2 / HTTP';

有时我们需要提供标题同时消耗发送的access_token API和很多事情就是用这个做方式:

  this.headers =新的报头();
this.headers.append(内容类型,应用/ JSON');
this.headers.append(授权,承载+ localStorage.getItem('id_token'))

现在来的 RequestMethods :bascially我们使用GET,POST,但我们有更多的选择,你可以的这里指...

我们可以通过使用使用requestmethods RequestMethod.method_name

有对API的,现在一些更多的选择我张贴的一个例子为POST通过使用一些重要的方法请求帮助:

  PostRequest(网址,数据){
        this.headers =新的报头();
        this.headers.append(内容类型,应用/ JSON');
        this.headers.append(授权,承载+ localStorage.getItem('id_token'))        this.requestoptions =新RequestOptions({
            方法:RequestMethod.Post,
            网址:网址,
            标题:this.headers,
            身体:JSON.stringify(数据)
        })        返回this.http.request(新请求(this.requestoptions))
            .MAP((RES:响应)=> {
                如果(RES){
                    返回[{状态:res.status,JSON:res.json()}]
                }
            });
    }

您可以太href=\"https://angular.io/docs/js/latest/api/http/Request-class.html\">指以获得更多信息。

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 want to add some more points so posting as answer.

first of all for consuminng Rest API's we need Http and HTTP_PROVIDERS module to import. if we are talking about Http 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 provided on the global level and available for the whole project like following.

bootstrap(App, [
    HTTP_PROVIDERS, some_more_dependency's
]);

and imports are from....

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 that is done using this way:

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

now come to RequestMethods: bascially we use GET, POST but we have some more option you can refer here...

we can use use requestmethods by using RequestMethod.method_name

there are some more option for the API's for now i posted one example for POST request the help 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.

这篇关于使用HTTP REST API的具有角2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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