17.10.2018 Views

Angular

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

ootstrap(AppComponent, [<br />

HTTP_PROVIDERS,<br />

{ provide: XHRBackend, useClass: InMemoryBackendService },<br />

{ provide: SEED_DATA, useClass: MockData }<br />

]);<br />

mock.service.ts<br />

Example of calling a get request for the created API route<br />

import { Injectable } from '@angular/core';<br />

import { Http, Response } from '@angular/http';<br />

import { Mock } from './mock';<br />

@Injectable()<br />

export class MockService {<br />

// URL to web api<br />

private mockUrl = 'app/mock';<br />

constructor (private http: Http) {}<br />

getData(): Promise {<br />

return this.http.get(this.mockUrl)<br />

.toPromise()<br />

.then(this.extractData)<br />

.catch(this.handleError);<br />

}<br />

private extractData(res: Response) {<br />

let body = res.json();<br />

return body.data || { };<br />

}<br />

}<br />

private handleError (error: any) {<br />

let errMsg = (error.message) ? error.message :<br />

error.status ? `${error.status} - ${error.statusText}` : 'Server error';<br />

console.error(errMsg);<br />

return Promise.reject(errMsg);<br />

}<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 128

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!