我的角度函数在第一次调用时没有执行.它仅在第二次调用时执行



标题真的不清楚,我同意你。 我在一个组件中有一个变量,我想在另一个组件中使用它。 我创建了一个可观察的服务,以便能够传输我的数据。 我将数据发送到我的服务,然后前往将检索此数据的页面。

this.service.myMethod(this.ville);
this.router.navigateByUrl('tabs/resto-by-ville');

在我获取数据并像这样使用它的背后:

getDataByVille() {
this.service.myMethod$.subscribe((city) => {
this.city = city;
this.http.get<Etablissement[]>('http://127.0.0.1:8000/api/etablissements/' + this.city).subscribe((data) => {
this.dataByVille = data;
console.log(this.dataByVille);
});
});
}
ngOnInit() {
this.getDataByVille();
}

我的服务 :

export class GetDataByVilleService {
myMethod$: Observable<string>;
private myMethodSubject = new Subject<string>();
constructor() {
this.myMethod$ = this.myMethodSubject.asObservable();
}
myMethod(data) {
console.log(data);
this.myMethodSubject.next(data);
}

我的问题是,当我发送数据时,绝对没有任何反应。如果我重复第二次,它将起作用。 我不明白为什么它第一次不起作用。 你有想法吗?目前它对用户体验不是很友好

问题是主题不存储值,所以当你到达"tabs/resto-by-ville"页面时,发射已经发生了。

您应该使用 BehaviorSubject,而不是 Subject,例如:

private myMethodSubject = new BehaviorSubject <string>(null);

BehaviorSubject 存储您为其提供的最后一个值,并在您订阅后立即发出该值。

你得到的可观察模式都是错误的。它们应该像这样链接:

服务:

export class GetDataByVilleService {
getDataByVille(): Observable<Etablissement[]> {
return this.http.get<Etablissement[]>('http://127.0.0.1:8000/api/etablissements/' + this.city)
});
}

元件:

// Component under "tabs/resto-by-ville"
export class RestoByVilleComponent {
dataByVille: Etablissement[];
constructor(getDataByVilleService: GetDataByVilleService )
ngOnInit() {
this.getDataByVilleService.getDataByVille().subscribe(dataByVille => {
this.dataByVille = dataByVille;
});
}
}

无需从要从中导航的组件调用服务。

最新更新