Using http rest apis with angular 2
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 -
- How to deal with http status codes other than 200 in Angular 2.
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';
Angular2 HttpClient to consume Rest API
I got the solution.
@AJT_82 gave me the main clue.
As It was said in the app module (app.module.js
) file, my app was taking the data from an InMemory storage system.
When I commented this line:
//InMemoryWebApiModule.forRoot(InMemoryDataService)
it just started to get the data from the URL provided to the localhost:8080/heroes Rest API.
Sorry for making you waste your time.
How to call an rest api while bootstrapping angular 2 app
You can use APP_INITIALIZER to call a service method at bootstrap. You will require to define a provider
for it in your AppModule
.
Here is an example of how to do this.
StartupService (startup.service.ts)
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class StartupService {
private _startupData: any;
constructor(private http: Http) { }
// This is the method you want to call at bootstrap
// Important: It should return a Promise
load(): Promise<any> {
this._startupData = null;
return this.http
.get('REST_API_URL')
.map((res: Response) => res.json())
.toPromise()
.then((data: any) => this._startupData = data)
.catch((err: any) => Promise.resolve());
}
get startupData(): any {
return this._startupData;
}
}
AppModule (app.module.ts)
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { StartupService } from './startup.service';
// ...
// Other imports that you may require
// ...
export function startupServiceFactory(startupService: StartupService): Function {
return () => startupService.load();
}
@NgModule({
declarations: [
AppComponent,
// ...
// Other components & directives
],
imports: [
BrowserModule,
// ..
// Other modules
],
providers: [
StartupService,
{
// Provider for APP_INITIALIZER
provide: APP_INITIALIZER,
useFactory: startupServiceFactory,
deps: [StartupService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
EDIT (How to handle startup service failure):
AppComponent (app.component.ts)
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { StartupService } from './startup.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private router: Router, private startup: StartupService ) { }
ngOnInit() {
// If there is no startup data received (maybe an error!)
// navigate to error route
if (!this.startup.startupData) {
this.router.navigate(['error'], { replaceUrl: true });
}
}
}
Fetching data from REST Web Service using Angular 2 Http
Since http requests are async, this.jsonData
won't be set at the time where you try to log it to console. Instead put that log into the subscribe callback:
getData(myArg: string){
this._myService.fetchData(myArg)
.subscribe(data => {
this.jsonData = JSON.stringify(data)
console.log(this.jsonData);
},
error => alert(error),
() => console.log("Finished")
);
}
Express rest api call with angular 2 How to
The Http get takes only url and not body as parameter.It is not a post to have body.
Try:
let params: URLSearchParams = new URLSearchParams();
params.set('roomName', roomName);
return this
.http
.get(`/api/room/byName/${roomName}`)
.map((response: Response) => response.json());
Related Topics
Check If an Array Is Empty or Exists
Get the Index of the Object Inside an Array, Matching a Condition
How to Expose Iframe's Dom Using Jquery
How to Screenshot Website in JavaScript Client-Side/How Google Did It? (No Need to Access Hdd)
Difference Between Using Bracket ('[]') and Dot ('.') Notation
Converting .Net Datetime to JSON
Document.All VS. Document.Getelementbyid
How to Strip All Punctuation from a String in JavaScript Using Regex
How to Use Ajax to Do File Upload
How to Convert the "Arguments" Object to an Array in JavaScript
JavaScript - How to Extract Filename from a File Input Control
How to Copy Static Files to Build Directory with Webpack
Are Braces Necessary in One-Line Statements in JavaScript
Ajax Mailchimp Signup Form Integration
JSON.Stringify Doesn't Work with Normal JavaScript Array
Is There a Built-In Way to Loop Through the Properties of an Object