【发布时间】:2019-09-24 22:05:26
【问题描述】:
我有以下例子:
数据模型:
export interface SampleList {
readonly Id: number;
CompanyName: string;
Country: string;
}
组件:
export class AppComponent implements OnInit {
private sampleList = new SampleWrapper<SampleList>();
constructor() { }
ngOnInit() {
this.sampleList.loadData('v_ListOfCompanies');
}
}
包装类:
export class SampleWrapper<T> {
public changes: T;
public original: T;
private sampleSvc: SampleService;
constructor() { }
public loadData(dbView: string) : void {
this.sampleSvc.getData<T>(dbView)
.subscribe(
data => {
this.original = data;
},
error => {
console.log(error);
}
);
}
}
服务:
export class SampleService {
static readonly apiUrl: string = environment.apiUrl;
constructor(private http: HttpClient) { }
getData<T>(dbView: string) : Observable<T> {
const url = `${SampleService.apiUrl}/${dbView}`;
return this.http.get<T>(url);
}
}
http-Requests 失败,因为 sampleSvc 未定义。
ERROR TypeError: "this.sampleSvc is undefined"
如何在包装类中使用 ApiService?谁能帮我?或者给我一些关于在 typescript 特别是 Angular 7 中使用泛型类的建议?
【问题讨论】:
标签: angular typescript generics angular7 wrapper