我通過下面的代碼使用打字稿延伸的Javascript基本陣列對象用於角應用程式:擴展陣列工作在角組件視圖中,但不是角組件類
文件:utilities.ts
// --- Extends Array object to include a getIndexBy method. ---
interface Array<T> {
getIndexBy(name: string, value: T): number;
}
// --- Returns the index of an object based on the name and value passed into the method.
Array.prototype.getIndexBy = function(name, value) {
for (let i = 0; i < this.length; i++) {
if (this[i][name] === value) {
return i;
}
}
};
文件:app.component.ts
import { Component } from '@angular/core';
import 'utilities';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
items: Array<{ name: string, age: number }> = [{
name: 'steve',
age: 20
}, {
name: 'bob',
age: 12
}, {
name: 'john',
age: 40
}];
constructor() {
console.log(this.items.getIndexBy('age', 20));
// ERROR - Argument of type '20' is not assignable to parameter of type '{ name: string; age: number; }'
}
}
文件:app.component.html
<h1>
{{title}}
</h1>
<hr>
{{items.getIndexBy('age', 12)}} <!-- Works as expected -->
{{items.getIndexBy('name', 'john')}} <!-- Works as expected -->
爲什麼我可以在視圖中使用擴展數組方法,但不能在組件類中使用擴展數組方法?
我明白了。是的,我的意圖是讓getIndexBy方法接受第二個通用參數 – YOOOEE