在打字稿中如何在函数中编写http服务
in typescript How to write http service in function
这里我知道如何以这种方式使用 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;
}
你需要做一个服务来请求数据并获取,然后使用组件内部的服务来获取数据,
您的示例服务应该是,
@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);
这里我知道如何以这种方式使用 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;
}
你需要做一个服务来请求数据并获取,然后使用组件内部的服务来获取数据,
您的示例服务应该是,
@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);