Angular 2 - 当我在模块中提供服务时如何将参数传递给抽象服务
带有抽象服务的文件
@Injectable()
export class Service<T>{
private headers: RequestOptions = headersRequest.options;
private readonly baseUrl: string;
constructor(private http: Http, baseUrl: string) {
this.baseUrl = baseUrl;
}
public getAll(): Promise<T[]> {
return this.http.get(`${this.baseUrl}`)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
public get(id: number): Promise<T> {
return this.http.get(`${this.baseUrl}`)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(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 Promise.reject(errMsg);
}
}
我提供服务时带模块的文件
@NgModule({
imports: [
SharedModule,
RouterModule.forChild(routes)
],
declarations: [
HeaderTennisComponent,
TennisComponent,
ProgramsComponent,
ProgramComponent,
PlotsComponent,
GuidesComponent,
CategoriesComponent,
ChampionsComponent
],
providers: [Service]
})
使用服务时带有组件的文件。
export class ProgramComponent implements OnInit {
private program: IProgram;
constructor(private route: ActivatedRoute, private tennisService: Service<IProgram>) {
//
}
public ngOnInit() {
this.getProgram(+this.route.snapshot.params['id']);
}
private getProgram(id: number) {
this.tennisService.get(id).then(
(program) => this.program = program
);
}
}
我提供服务时需要传递 baseUrl。