Javascript 当赋值的右侧有值时,未定义赋值
我在angular中有一个组件,它使用Javascript 当赋值的右侧有值时,未定义赋值,javascript,angular,typescript,Javascript,Angular,Typescript,我在angular中有一个组件,它使用ngOnInit函数上的服务。当我从服务调用一个方法时,它返回一个元素数组并将其分配给t变量,我确认它正在返回数组,但我使用t变量并将其分配给一个类型化变量,但分配后,类型化变量保留未定义的值 组成部分: export class HeroesFilteredComponent implements OnInit { private heroes:Heroe[]; private termino:string; constructor(
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
时,它有值
为什么会有这种奇怪的行为?console.log(this.heroes.length)代码>写入HeroesFilteredComponent
中的subscribe
块之外。这就是为什么它是未定义的
将其移动到subscribe
块中,它将打印正确的值
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);
});
}
}
console.log(this.heroes.length)代码>写入HeroesFilteredComponent
中的subscribe
块之外。这就是为什么它是未定义的
将其移动到subscribe
块中,它将打印正确的值
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);
});
}
}
该代码不足以提供答案。是否存在异步进程?您必须提供更多的代码,因为您所描述的内容与您发布的简单代码不符。好的,让我来编辑。@julianzapata,您能在StackBlitz示例中复制此内容吗?这些代码的信息不足以给出答案。是否存在异步进程?您必须提供更多的代码,因为您所描述的内容对于您发布的简单代码没有意义。好的,让我来编辑。@julianzapata,您可以在示例StackBlitz上复制它吗?但我指的是范围参数。我只是在修改它的价值。我尝试了你的解决方案,但我遇到了同样的错误。@julianzapata,console.log
行写在subscribe
块之外。subscribe
块中的代码将在console.log
之后运行。由于console.log
将在组件上设置heros
属性之前运行,因此您会在控制台上看到undefined。谢谢@siddAjmera。真的,这不是问题,但请帮我解决。原因是我从未将值传递给另一个组件,但我从未在那里查看,因为在调试时,这个未定义的值,并且我正在用错误重新关联这个值。但是我引用的是作用域参数。我只是在修改它的价值。我尝试了你的解决方案,但我遇到了同样的错误。@julianzapata,console.log
行写在subscribe
块之外。subscribe
块中的代码将在console.log
之后运行。由于console.log
将在组件上设置heros
属性之前运行,因此您会在控制台上看到undefined。谢谢@siddAjmera。真的,这不是问题,但请帮我解决。原因是因为我从未将值传递给输入变量到另一个组件,但我从未查看过,因为在调试时,这个未定义的值与错误相关。