简体   繁体   English

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

[英]Angular NgOnInit executing method before another

I have an angular application where I am trying to get an array of sources for an image carousel.我有一个 angular 应用程序,我试图在其中获取图像轮播的一组源。 How I have it set up currently I have a "getUrls()" method to get the urls from the database like so我目前是如何设置的 我有一个“getUrls()”方法来从数据库中获取网址,就像这样

http.service.ts: http.service.ts:

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

That method calls the method "setUrls" to set them into an array stored in a service该方法调用方法“setUrls”将它们设置为存储在服务中的数组

carousel.service.ts:旋转木马.service.ts:

  urls: string[] = [];

  constructor() {}

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

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

Then inside of the carousel component I call both of the previous methods in ngOnInit然后在 carousel 组件内部,我在 ngOnInit 中调用了之前的两个方法

image-carousel.component.ts:图像轮播.component.ts:

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

This would then assign the values set by the "setUrls()" method, but for some reason, it is reaching the "getImages()" method before setting the Urls.然后这将分配由“setUrls()”方法设置的值,但由于某种原因,它在设置 Urls 之前到达“getImages()”方法。

I got it to work by taking the "getImages()" line into a separate method and clicking a button to call it, so that I could make sure that everything worked in the right order and it did, however I want it to do all of that when the components are initialized.我通过将“getImages()”行放入一个单独的方法并单击一个按钮来调用它来让它工作,这样我就可以确保一切都按正确的顺序工作并且确实如此,但是我希望它完成所有工作当组件被初始化时。

I am sure I am missing something, so anything helps, even if I have to refactor a lot.我确信我遗漏了一些东西,所以任何东西都有帮助,即使我必须进行大量重构。

I tried to use a ".pipe(tap()" in the "getUrls()" method instead of a subscribe, however it would never call the "setUrls()" method.我尝试在“getUrls()”方法中使用“.pipe(tap()”而不是订阅,但它永远不会调用“setUrls()”方法。

Since getUrls() perform its work asynchronously, you have no idea when it completes and return imageUrls .由于getUrls()以异步方式执行其工作,因此您不知道它何时完成并返回imageUrls You'll have to refactor your code a little, like this你必须像这样重构你的代码

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

and your ngOnInit method would get updated like this你的 ngOnInit 方法会像这样更新

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

http.service.ts: http.service.ts:

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

carousel.service.ts:旋转木马.service.ts:

  urls: string[] = [];

  constructor() {}

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

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

image-carousel.component.ts:图像轮播.component.ts:

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

The function in the service getUrls() is an asynchronous one.服务getUrls()中的 function 是异步的。 Therefore you have to wait for it to be resolved.因此,您必须等待它被解决。 You can use the observables for this to achieve.您可以使用 observables 来实现。 You need to simply subscribe the getUrls() and put the get images function call in the subscription block.您只需订阅getUrls()并将获取图像 function 调用放在订阅块中。

As getUrls() performing a asynchronous task which is http.get ,you have to wait to get images until asynchronous task gets completed.由于getUrls()执行异步任务http.get ,您必须等待异步任务完成才能获取图像。

So one of the possible solution could be,you can return observable from your http.service.ts service and inside component ngOnInit you can fetch images inside subscription.因此,一种可能的解决方案是,您可以从http.service.ts服务返回 observable,并在组件ngOnInit内部获取订阅内的图像。

http.service.ts: http.service.ts:

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

carousel.service.ts:旋转木马.service.ts:

  urls: string[] = [];

  constructor() {}

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

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

image-carousel.component.ts:图像轮播.component.ts:

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

暂无
暂无

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

相关问题 firebase方法结束前另一个方法运行的问题reactjs - Problem of another method runs before the firebase method finishes reactjs 执行get request firebase时出错,error: 'Unauthorized request in Angular - Error while executing get request firebase, error: 'Unauthorized request in Angular 如何在执行任务之前等待多个 firebase 查询完成? - How to wait for multiple firebase queries to finish before executing a task? 如何等到从 Firebase 下载完成后才执行完成 swift - How to wait till download from Firebase Storage is completed before executing a completion swift Firebase 中的异步 function 甚至在 function 主体完成执行之前就解析了 promise - Async function in Firebase resolves the promise even before the function body has finished executing NgOnInit() 在构造函数之后/与构造函数并行运行 - NgOnInit() Runs after/in parallel with constructor 如何在运行函数之前等待数据从 Firestore 加载 Angular - How to wait for data to be loaded from Firestore before running functions Angular 执行另一个步骤函数的地图不传递任何输入 - Map executing another step function does not pass any input Select 从最后一个寄存器到另一列中另一个寄存器之前的时间 - Amazon redshift - Select the time from the last register before another register in another column - Amazon redshift 如何让我的程序在执行 function 之前等待 Firebase 的数据? - How can make my Program wait for Firebase's data before executing a function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM