32

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.

SeleM
  • 9,310
  • 5
  • 32
  • 51
Ilja
  • 44,142
  • 92
  • 275
  • 498
  • 1
    add the HTTP_PROVIDERS in your boot file and make sure you added the http.dev.js library and change the `@Inject(Http) http` for `http:Http` – Langley Jan 12 '16 at 23:02
  • 1
    The error you are getting is because you are importing `@Injectable` but not `@Inject` and you are using both – Langley Jan 12 '16 at 23:08
  • @Langley Could you expand n your coment please? http.dev.js needs to be aded as script in index.html? and I am not sure how I need to change the second part. – Ilja Jan 12 '16 at 23:14
  • 1
    Added them as an answer, more readable that way. – Langley Jan 12 '16 at 23:21
  • Here is an article about Http if you are interested http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http – TGH Jan 13 '16 at 01:02

2 Answers2

36

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';
Community
  • 1
  • 1
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
7

You need to add this line:

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

in your index.html file.

You need to add HTTP_PROVIDERS:

bootstrap(App, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS
]);

in your boot.ts/bootstrap.ts file, and import them of course.

You need to import @Inject in your DojoService class file:

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

Just like you imported @Injectable.

Langley
  • 5,326
  • 2
  • 26
  • 42