-2

I asked this question on how to solve ReferenceError: google is not defined. The most important part of the code is the following:

ngOnInit() {
        this.someContentWithAddress$ = this.someServiceWithContent.someContentWithAddress$.pipe(
            tap(someContentWithAddress => {
                this.address = someContentWithAddress.address;
                setTimeout(() => {
                    this.calculateAddress(this.address);
                }, 1000);
            })
        );
    }

I'm using setTimeout() to solve the error, but it seems to me that this approach is not a good one.

Also the answer in the recommended post doesn't work for me (still getting the same error). I also don't want to use scripts to solve the problem.

Is there another way (that hopefully also works) to solve it?

Constantin Beer
  • 5,447
  • 6
  • 25
  • 43

1 Answers1

1

A solution to the problem can be found here.

After installing @types/ggoglemaps like this:

npm install --save @types/googlemaps

the MapsAPILoader must be passed through the constructor and the load() method of it has to be used in ngOnInit() instead setTimeout().

export class MyComponent implements OnInit {

    ...

    constructor(
        private readonly someServiceWithContent: SomeServiceWithContent
        private mapsApiLoader: MapsAPILoader) {
    }

    ngOnInit() {
        this.someContentWithAddress$ = this.someServiceWithContent.someContentWithAddress$.pipe(
            tap(someContentWithAddress => {
                this.address = someContentWithAddress.address;
                this.mapsApiLoader.load().then(() => {
                this.calculateAddress(this.address);
                });
            })
        );
    }

...

}
Constantin Beer
  • 5,447
  • 6
  • 25
  • 43