2017-04-15 88 views
0

在這裏寫下的http服務,我知道後以這種方式使用HTTP服務,但我怎麼能當其功能如同在打字稿如何在功能

export class studentController { 

     GetStudentData() { 
     constructor(http: Http) { 
      http.get('api/Employee').subscribe(result => { 

       this.student = result.json(); 
      }) 
     } 
    } 


export class StudentMastre { 
    stdID: Number; 
    stdName: string; 
    email: string; 
    Phone: string; 
    Address: string; 
} 

回答

1

你需要做一個服務請求寫服務數據得到,然後使用該服務的組件內部來獲取數據,

你的樣品服務應該是,

@Injectable() 
export class CategoryService { 
    constructor(private http: Http) { } 
c(): Observable<StudentMastre[]> { 
     let wikiUrl = return this.http 
      .get('api/Employee') 
      .map(this.extractData) 
      .catch(this.handleErrors); 
    } 
private extractData(res: Response) { 
     let data = res.json(); 
     return data; 
    } 

    private handleErrors (error: Response | any) { 
     let errMsg: string; 
     if (error instanceof Response) { 
      const body = error.json() || ''; 
      const err = body.error || JSON.stringify(body); 
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
     } else { 
      errMsg = error.message ? error.message : error.toString(); 
     } 
     console.error(errMsg); 
     return Observable.throw(errMsg); 
    } 

然後在您的組件,

this.sampleService. 
this.categoryService.getCategoriesService().subscribe(students=> { 
    this.students= students; 
}, error => this.errorMessage = error);