简体   繁体   English

使用 Angular 可观察到的重新加载页面崩溃

[英]Page Crash on reload with Angular Observable

I have a Method in a Service which looks like this我在服务中有一个方法,看起来像这样

public getAnwendungZuClientId(clientId: string, nurBerechtigteAnwendungen: boolean = true): Observable<Anwendung> {
const anwObservable = this.prüfeObNurBerechtigt(nurBerechtigteAnwendungen);

let observableToReturn: Observable<Anwendung>;

observableToReturn = anwObservable
.pipe(
  map((anwendungen: Anwendung[]) => {
      return anwendungen
        .find(anwendung => {
            return anwendung.client_id === clientId
        })
      }
    ),
  first()
);

return observableToReturn;

} }

It returns an Observable<Anwendung> .它返回一个Observable<Anwendung> In my component I just call this service Methode to make it available in the View在我的组件中,我只是调用此服务 Methode 以使其在视图中可用

getAnwendungByClientId (anwendungId: string): Observable<Anwendung> {
    return this.anwendungService.getAnwendungZuClientId(anwendungId);
  }

And consume it in a View with an async Pipe并在带有异步 Pipe 的视图中使用它

{{ (getAnwendungByClientId(anwendung.clientId) | async).name }}

It works if I navigate from another page to the page with the component which includes the observable.如果我从另一个页面导航到包含 observable 的组件的页面,它会起作用。 But if i call the route directly, or reload, the page crashes without a specific error.但是,如果我直接调用路由或重新加载,页面会崩溃而没有特定错误。 Does anybody know where the Problem, in directly calling that route, is?有谁知道直接调用该路线的问题在哪里?

页面崩溃

I guess Angular tries to call getAnwendungByClientId in every change detection cycle, which in turn causes a new subscription to the Observable, which in turn creates a new change detection cycle.我猜 Angular 尝试在每个更改检测周期中调用getAnwendungByClientId ,这反过来又会导致对 Observable 的新订阅,这反过来又会创建一个新的更改检测周期。 So you'll get an endless loop which probably crashes your browser.所以你会得到一个可能导致浏览器崩溃的无限循环。

Try calling getAnwendungByClientId in your component's ngOnInit and store the return Observable as a class property of the component.尝试在组件的ngOnInit中调用getAnwendungByClientId并将返回的 Observable 存储为组件的 class 属性。 Then, subscribe to that class property in your template.然后,订阅模板中的 class 属性。

Something like:就像是:

private obs$: Observable<Anwendung>

ngOnInit() {
  // don't know where `anwendung` comes from but you need it here :)
  this.obs$ = getAnwendungByClientId(anwendung.clientId)
}

In your template在您的模板中

{{ (obs$| async).name }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM