我有一個@Injectable
類,在Service.ts中創建一個獲取函數。這個函數應該返回一個數組,並獲得任何數組。但它返回null
。如果我直接在@Component
中寫這個,那麼它會得到數組。我究竟做錯了什麼?Angular2 @Injectable not working
service.ts
@Injectable()
export class Arr_selected {
private arr = [];
get(arr_selected: any[]){
for(let key in arr_selected) {
if (arr_selected.hasOwnProperty(key)) {
this.arr.push([key]);
return this.arr;
}
}
console.log(this.arr);
}
}
component.ts
import {Arr_selected} from './service.ts';
export class Component implements DoCheck, OnChanges, OnInit {
....
constructor(public arr_selected: Arr_selected)
.....
ngOnInit{
let chk = this.ChkBoxValue;
let arr = [];
/// **this not working Array is null**/////
arr=(this.arr_selected.get(this.ChkBoxValue));
/// **this is working Array is not null**////
for (let key in this.ChkBoxValue) {
if (this.ChkBoxValue.hasOwnProperty(key)) {
arr.push(this.ChkBoxValue[key]);
}
}
console.log(arr);
}}
您是否正在導入服務並將其注入到組件中? –
謝謝,是的,我正在導入 - > import {Arr_selected} from ./ servece.ts; – ran
也許是一個沉睡者? – elvin