我是Angular世界的新手。我有一个简单的应用程序,只需查询数据库,然后在表中显示数据即可。这是来自服务以运行查询(db.service.ts)的代码:
query(): Observable<printerResults[]>{
return this.http.get<printerResults[]>(this.dataURL);
};
来自我的组件(Printer-component.ts的调用:
results: printerResults[];
ngOnInit() {
this.getData();
};
getData(): void {
this.TestService.query()
.subscribe((res: printerResults[]) => {this.results = res}, err =>
console.log("error"));
}
我的类声明(Results.ts):
export class printerResults {
Cell: string;
Plant: string;
PrinterDPI: number;
PrinterName: string;
PrinterType: string;
}
如果我将console.log放在订阅中,例如:
.subscribe(res => console.log(res), err =>
console.log("error"));
它显示了完整的对象。但是当我尝试在html端使用它时,我得到了[object Object]。任何帮助,将不胜感激。
解析管道中的json,因此订阅中将包含一个对象,而不是json字符串。
results: printerResults[];
ngOnInit() {
this.getData();
};
getData(): void {
this.TestService.query()
.map( _res => JSON.parse(_res) )
.map( _res => _res.map( _raw => PrinterResults.initFromJsonRaw( _raw ) ) )
.subscribe((res: printerResults[]) => {this.results = res}, err =>
console.log("error"));
}
打印机结果
class PrinterResults...
public static initFromJsonRaw(_object) : PrinterResults {
let ret = new PrinterResults();
ret.PrinterName = _object.name;
ret.PrinterDPI = _object.dpi;
return ret;
}
}
然后在模板中,仅插入结果数据。ngFor循环它,因为,它似乎是代码中的数组。
.html
<ng-container *ngFor="let result of results">
<p>Name: {{ result.PrinterName }}</p>
<p>DPI: {{ result.PrinterDPI }}</p>
</ng-container>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句