我有一个角度组件,消耗 ngOnInit
函数上的服务 . 当我从服务中调用一个方法时,它返回一个元素数组并将其分配给 t
变量,并且我确认它正在返回数组,但是我接受了 t
变量并将其分配给了一个类型变量,但在赋值后,键入的变量保留未定义的值 .
零件:
export class HeroesFilteredComponent implements OnInit {
private heroes:Heroe[];
private termino:string;
constructor(
private _heroesService:HeroesService,
private _activatedRoute:ActivatedRoute
) { }
ngOnInit() {
this._activatedRoute.params.subscribe(params =>{
let t = this._heroesService.searchHeroes(params['g']);
this.heroes = t;
});
console.log(this.heroes.length);
}
}
服务:
@Injectable()
export class HeroesService {
private heroes:Heroe[] = [{...},...,{...}]
searchHeroes(termino:string):Heroe[]{
termino = termino.toLowerCase();
return this.heroes;
}
}
接口:
export interface Heroe{
nombre:string;
bio:string;
img:string;
aparicion:string;
casa:string;
index?:number;
}
当我检查 t
时,它有 Value .
为何这种奇怪的行为?
1 回答
console.log(this.heroes.length);
写在HeroesFilteredComponent
的subscribe
块之外 . 这就是它未定义的原因 .将其移到
subscribe
块内,它应该打印正确的值 .