繁体   English   中英

Angular NgOnInit 在另一个方法之前执行

[英]Angular NgOnInit executing method before another

我有一个 angular 应用程序,我试图在其中获取图像轮播的一组源。 我目前是如何设置的 我有一个“getUrls()”方法来从数据库中获取网址,就像这样

http.service.ts:

getUrls() {
    this.http
      .get<string[]>(
        '<DATABASE_LINK>'
      )
      .subscribe((imageUrls: string[]) => {
        this.carouselService.setUrls(imageUrls);
      });
  }

该方法调用方法“setUrls”将它们设置为存储在服务中的数组

旋转木马.service.ts:

  urls: string[] = [];

  constructor() {}

  setUrls(urls: string[] | []) {
    this.urls = urls || [];
    debugger;
  }

  getImages() {
    debugger;
    return this.urls;
  }

然后在 carousel 组件内部,我在 ngOnInit 中调用了之前的两个方法

图像轮播.component.ts:

  ngOnInit(): void {
    this.httpService.getUrls();
    this.images = this.cService.getImages();
  }

然后这将分配由“setUrls()”方法设置的值,但由于某种原因,它在设置 Urls 之前到达“getImages()”方法。

我通过将“getImages()”行放入一个单独的方法并单击一个按钮来调用它来让它工作,这样我就可以确保一切都按正确的顺序工作并且确实如此,但是我希望它完成所有工作当组件被初始化时。

我确信我遗漏了一些东西,所以任何东西都有帮助,即使我必须进行大量重构。

我尝试在“getUrls()”方法中使用“.pipe(tap()”而不是订阅,但它永远不会调用“setUrls()”方法。

由于getUrls()以异步方式执行其工作,因此您不知道它何时完成并返回imageUrls 你必须像这样重构你的代码

getUrls():Observable<string[]> {
return this.http
  .get<string[]>(
    '<DATABASE_LINK>'
  );
  }

你的 ngOnInit 方法会像这样更新

  ngOnInit(): void {
this.httpService.getUrls()
.subscribe((imageUrls:string[])=>
 {
   this.images = imageUrls;
  });
 }

http.service.ts:

getUrls() {
    return this.http
      .get<string[]>(
        '<DATABASE_LINK>'
      )
      .pipe(
         map((imageUrls: string[]) => {
            this.carouselService.setUrls(imageUrls);
         })  
       );
  }

旋转木马.service.ts:

  urls: string[] = [];

  constructor() {}

  setUrls(urls: string[] | []) {
    this.urls = urls || [];
    debugger;
  }

  getImages() {
    debugger;
    return this.urls;
  }

图像轮播.component.ts:

ngOnInit(): void {
    this.httpService
        .getUrls()
        .subscribe(
          () => {
             this.images = this.cService.getImages();
          }
        );
  }

服务getUrls()中的 function 是异步的。 因此,您必须等待它被解决。 您可以使用 observables 来实现。 您只需订阅getUrls()并将获取图像 function 调用放在订阅块中。

由于getUrls()执行异步任务http.get ,您必须等待异步任务完成才能获取图像。

因此,一种可能的解决方案是,您可以从http.service.ts服务返回 observable,并在组件ngOnInit内部获取订阅内的图像。

http.service.ts:

getUrls() {
    return this.http
      .get<string[]>(
        '<DATABASE_LINK>'
      )
      .pipe(
         map((imageUrls: string[]) => {
            this.carouselService.setUrls(imageUrls);
         })  
       );
  }

旋转木马.service.ts:

  urls: string[] = [];

  constructor() {}

  setUrls(urls: string[] | []) {
    this.urls = urls || [];
    debugger;
  }

  getImages() {
    debugger;
    return this.urls;
  }

图像轮播.component.ts:

ngOnInit(): void {
    this.httpService
        .getUrls()
        .subscribe(
          () => {
             this.images = this.cService.getImages();
          }
        );
  }

暂无
暂无

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

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