我有一个@Injectable
类,在Service.ts中有一个get-function创建。此函数应返回一个Array并获取任何数组。但它返回null
。如果我直接在@Component
中写这个,那么它确实得到了数组。我究竟做错了什么?
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);
}}
答案 0 :(得分:0)
我认为以下应该有效
@Injectable()
export class Arr_selected {
get(arr_selected: any[]){
arr = [];
for(let key in arr_selected) {
if (arr_selected.hasOwnProperty(key)) {
arr.push([key]);
return this.arr;
}
}
console.log(this.arr);
}
我认为“this”运算符会导致问题。您还在组件中定义了arr。这可能是相互矛盾的。
答案 1 :(得分:0)
Above code you have written your file name as service.ts
并从./servece.ts
导入 import {Arr_selected} from'./servece.ts;
这可能是它的输入错误, 您也在组件提供商中添加服务吗?。