Max*_*Max 22 javascript typescript angular
我现在真的很困惑,因为我得到了ERROR TypeError: "_this.device.addKeysToObj is not a function".但我实现了这个功能,所以我不知道问题是什么或为什么它不可调用.我已经尝试使用Firefox和chrome的代码,两者都是通过相同的错误.
错误符合 this.device.addKeysToObj(this.result.results[0]);
这是我的班级:
export class Device {
id: number;
deviceID: string;
name: string;
location: string;
deviceType: string;
subType: string;
valueNamingMap: Object;
addKeysToObj(deviceValues: object): void {
for (let key of Object.keys(deviceValues).map((key) => { return key })) {
if (!this.valueNamingMap.hasOwnProperty(key)) {
this.valueNamingMap[key] = '';
}
}
console.log(this, deviceValues);
}
}
Run Code Online (Sandbox Code Playgroud)
这就是电话:
export class BatterieSensorComponent implements OnInit {
@Input() device: Device;
public result: Page<Value> = new Page<Value>();
//[..]
ngOnInit() {
this.valueService.list('', this.device).subscribe(
res => {
console.log(this.device); // NEW edit 1
this.result = res;
if (this.result.count > 0)
{
this.device.addKeysToObj(this.result.results[0]);
}
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
编辑1
记录this.device在上面的代码中看到评论:
{
deviceID: "000000001"
deviceType: "sensor" ?
id: 5 ?
location: "-"
? name: "Batteries" ?
subType: "sensor" ?
valueNamingMap:
Object { v0: "vehicle battery", v1: "Living area battery" }
<prototype>: Object { … }
}
Run Code Online (Sandbox Code Playgroud)
编辑2
device.service代码的一部分:
list(url?: string, deviceType?: string, subType?: string): Observable<Page<Device>> {
if(!url) url = `${this.url}/devices/`;
if(deviceType) url+= '?deviceType=' + deviceType;
if(subType) url+= '&subType=' + subType;
return this.httpClient.get<Page<Device>>(url, { headers: this.headers })
.pipe(
catchError(this.handleError('LIST devices', new Page<Device>()))
);
}
Run Code Online (Sandbox Code Playgroud)
父组件中的调用:
ngOnInit() {
this.deviceService.list('', 'sensor', ).subscribe(
res => {
this.devices = res.results;
}
)
}
Run Code Online (Sandbox Code Playgroud)
模板:
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--6-col mdl-cell--6-col-tablet" *ngFor="let device of devices">
<app-batterie-sensor [device]="device"></app-batterie-sensor>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Unc*_*ave 38
这是一个常见的关于Typescript的问题,你说device是类型的Device,但事实并非如此.它具有与遗嘱相同的所有属性Device,但由于它实际上Device并不是它没有预期的方法.
您需要确保为您Device的每个条目实例化Page,可能在ngOnInit父组件中:
我不知道它的结构Page,但如果它是一个数组,请尝试以下方法.
ngOnInit() {
this.deviceService.list('', 'sensor', ).subscribe(
res => {
this.devices = res.results.map(x => Object.assign(new Device(), x));
}
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24817 次 |
| 最近记录: |