angularjs - Move http functionaity into its own Service with Angular2 and TypeScript -


i'm trying teach myself angular2 , typescript after happily working angular 1.* last 4 years! anyway, have top level component creates property derived type have created in class. component when ngoninit() called make http call phoney rest service wrote end. when writing apps using angularjs put $http tasks service , inject them controllers... same component. here's component without service code activated... notice comments

import {component, oninit} 'angular2/core'; import {routeconfig, router_directives} 'angular2/router'; import {home} './components/home/home'; import {userstatus} './types/types.ts'; // why userstatus type kept import {userdata} './services/user-data/userdata.ts'; // here wish write sevice perform http tasks... import {http, headers} 'angular2/http';  @component({     selector: 'app', // <app></app>     providers: [...form_providers],     directives: [...router_directives],     pipes: [],     styles: [require('./app.scss')],     template: require('./app.html') })  export class app {      userstatus: userstatus;      constructor(public http: http) {         this.userstatus = new userstatus();     }      ngoninit() {          // want put code seperate class , provide service...         var headers = new headers();         headers.append('content-type', 'application/json');         this.http.get('/restservice/userstatus', {headers: headers})             .map((data: any) => data.json())             .subscribe(             (data: any) => {                 this.userstatus = data;             },             err => console.log(err), // error             () => console.log('getuserstatus complete') // complete          );          /* i'd factor above service kept in diffent file so*/         /*           userdata.getuserstatus().then((resp) => {             this.userstatus = resp;          })          */      } } 

now here type... userstatus property...

export class userstatus {      constructor (         public firstname?: string,         public fullpersid?: number,         public golduser?: boolean,         public hasprofileimage?: boolean,         public hidemoblienavigationandfooter?: boolean,         public persid?: string,         public profilename?: string,         public profilepicture?: string,         public showads?: boolean,         public siteid?:  number,         public url?: string,         public verified?: boolean,         public appos?: any,         public formername?:     ) {          this.firstname = firstname || '';         this.fullpersid = fullpersid || 0;         this.golduser = golduser || false;         this.hasprofileimage = hasprofileimage || false;         this.hidemoblienavigationandfooter = hidemoblienavigationandfooter || false;         this.persid = persid || '';         this.profilename = profilename || '';         this.profilepicture = profilepicture || '';         this.showads = showads || false;         this.siteid =  siteid || 0;         this.url = url || '';         this.verified = verified || false;         this.appos = appos || null;         this.formername = formername || null;      } } 

now wish put http functionality of component serperate service... started write following code (please don't laugh, new angular2)

import {injectable} 'angular2/core'; import {http, headers} 'angular2/http'; import {userstatus} '../../types/types.ts';  @injectable() export class userdata {      constructor(public http:http) {     }      getuserstatus(): {         var headers = new headers();         headers.append('content-type', 'application/json');         this.http.get('/restservice/userstatus', {headers: headers})             .map((data: any) => data.json())             .subscribe(             (data: any) => {                 return data;             },             err => console.log(err), // error             () => console.log('getuserstatus complete') // complete         );     } } 

now hoping call service getuserstatus() method perform http data fetch , call in app component (i using angularjs 1.x promise example, know should use observables... don't know how!)

ngoninit() {       userdata.getuserstatus().then((resp) => {         this.userstatus = resp;      });      } 

this rubbish , don't know doing (examples/tutorials angular2 don't seem great or practical far). can please show how wire service call correctly in component?

i question because went down same road , had refactor code. best practice right rxjs observables not return json in .subscribe() method http request. map , return it. doing there stripping of info has.

you supposed return observable whole implementation of get().

getuserstatus(): {         var headers = new headers();         headers.append('content-type', 'application/json');         return this.http.get('/restservice/userstatus', {headers: headers})             .map((data: any) => data.json())             .catch(this.handleerror)         );     }  private handleerror(error: response) {     // in real world app, may send server remote logging infrastructure     // instead of logging console     console.error(error);     return observable.throw(error.json().error || 'server error');   } 

then on component side can subscribe observable

export class app {     public userstatus:any;     // have inject userdata service our component here.     constructor(public http: http, private _userdata: userdata ) {     }      ngoninit() {          this._userdata.getuserstatus()          .subscribe(             (status) => {               this.userstatus = status;             },             (err) => {               console.log(err);             },             ()=>{console.log("user status complete")}          );          } } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -