What is a workaround to load data prior to rendering a page without the need for a resolver?

Having an issue where my object is not defined before the page renders. I am looking to load my data first and then render the page without using a resolver or ngIf. Could I utilize LifeCycle Hooks to achieve this?

Here is my current setup:

app.component.ts

  onNavigateToDetailView(url: string, title: string){
     this.service.getResourceUrl(url).subscribe( 
       (data) => {
         this.service.detailedObj = data;
         console.log(data);
       } 
     );
     this.router.navigate(['detailedview/' + title]);
  }

Now in my view.component.ts, I want to assign the object in my service to a variable:

ngOnInit(){
  this.obj = this.service.obj;
}

In my view.component.html, I have:

{{obj.text}}

It is not working because the object is undefined during rendering. If I were to use the object in my service like this

{{this.service.obj.text} 

it works, but I prefer not to use it.

So, is there a way to wait for the data to be defined and then render the page without using a Resolver or *ngIf? Could this be achieved with another LifeCycle Hook instead of ngOnInit?

Stackblitz: https://stackblitz.com/edit/angular-21zvgm

After navigating to hello.component, an empty object is output to the console. However, when you click show in hello.component, the object initializes correctly...

Answer №1

Utilize the async pipe:

In your TypeScript file:

data$: Observable<any>;

ngOnInit() {
  this.data$ = this.service.getResourceUrl(url);
}

And in your HTML:

{{(data$ | async)?.text}}

Answer №2

Upon reviewing your stackblitz and question, it seems that you require a route guard.

To address this, I have made adjustments to your getInfo service to now return a Promise.

  getInfo(title: string, type: string) {
    return this.http.get(...).toPromise()
      .then( data => {this.obj = data; return data; });
  }

In addition, I have developed a guard service and integrated the CanActivate method.

@Injectable({
  providedIn: "root"
})
export class AppGuardService implements CanActivate {
  constructor(private router: Router, private srv: MyserviceService) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.srv.getInfo("The Beatles", "artist")
      .then(() => return true; })
      .catch(error => {
        console.error(error);
        return false;
      });
  }
}

Furthermore, I have updated the routing to include the canActivate property:

{ path: "hello", component: HelloComponent, canActivate:[AppGuardService] }

You can access the complete stackblitz example at https://stackblitz.com/edit/angular-nazeby

Update:

Alternatively, if the scenario only requires a single navigation, you can modify the navigate function to handle the service data as a Promise, thus eliminating the need for the app-guard service and CanActivate.

  navigate(){
    this.srv.getInfo("The Beatles", "artist").then(
      () => this.router.navigate(["/hello"])
    )
  }

Happy Coding!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for showcasing images stored in Azure Blob storage

Currently, I am developing an application that requires loading images from a web novel stored in Azure Storage Accounts as blobs. While I have enabled anonymous reads to show the image upon request successfully via a web browser or Postman, I am facing an ...

Issue with React routing: When passing id params in the URL using history.push, it is returning undefined

Struggling with using history.push in an onClick event to pass user id to a Profile page component, but the uuid params in the URL are showing up as undefined. Feeling stuck at this point. I also need to include all other props obtained from the Random Us ...

Deactivate the chosen tab by clicking the Mat-Tab button

I was trying to implement a way to disable the selected mat-tab and its elements when a button is clicked, //HTML <mat-tab-group #tabGroup> <mat-tab *ngFor="let subject of subjects" [label]="subject.name"> {{ subject.name }} ...

angular2: The element 'Validators' is not recognized

When working with Angular2, I encountered an error in Visual Studio Code that is displayed with the following message: enter image description here Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module" ...

Having trouble downloading both an HTML file and a PDF file at the same time by clicking two separate buttons in an Angular 8 web API controller

I am encountering an issue with downloading files from my web application. I have two buttons - one for downloading a PDF file and another for downloading an HTML file. The problem arises when clicking on the link to download the HTML file first, as it do ...

Allow consumers of the component to customize the ChangeDetectionStrategy

Imagine a scenario where a component in a UI library is configured with ChangeDetectionStrategy.Default, but wants to offer the flexibility for consumers to switch to ChangeDetectionStrategy.OnPush (especially for performance considerations) using an Input ...

Can anyone provide assistance on implementing multiple where conditions in a loop with Firebase and Angular?

I've been attempting to implement dynamic conditions on a firebase query, but I'm having issues getting it to work. I even tried using chatgpt, but that didn't provide me with the ideal solution either. Can someone please assist me in resolv ...

Is the ngrx adapter compatible with composite primary keys?

I'm working on implementing a composite primary key for an entity. Is there a way to successfully use a composite primary key in this case? Here is my goal: // I want my entity, DailyEvent, to be uniquely identified by [year, month, dayofmonth] expor ...

Unusual Behavior of Observable.concat() in Angular 4 with RxJS 5

My Angular 4 / TypeScript 2.3 service has a method called build() that throws an error if a certain property is not initialized. I am attempting to create a safer alternative called safeBuild() that will return an Observable and wait for the property to be ...

Eliminating the dynamic element in jQuery causes disruption to the ViewContainerRef container

In my Angular 2+ application, I am dynamically creating components using the following code snippet: @ViewChild("containerNode", { read: ViewContainerRef }) cardContainer; const factory = this.ComponentFactoryResolver.resolveComponentFactory(CardComponen ...

Swap out each addition symbol with a blank space within a given text

I'm currently working on a Typescript project where I need to convert URL parameters into a JSON object. The issue I'm facing is that some values are concatenated with a '+'. How can I replace this symbol with a space? Here's the ...

What is the best way to detect object changes in typescript?

Having an object and the desire to listen for changes in order to execute certain actions, my initial approach in ES6 would have been: let members = {}; let targetProxy = new Proxy(members, { set: function (members, key, value) { console.log(k ...

Discover the method for dynamically setting the rangeSelector's min and max values multiple times in Angular Highcharts

I'm looking to dynamically set the range of an angular highstock chart by interacting with another component such as a table or button. For example, attempting to use setExtremes for selecting range T1 or T2 does not seem to work properly in this cod ...

The interface is incompatible with the constant material ui BoxProps['sx'] type

How can I make the interface work for type const material ui? I tried to register an interface for sx here, but it keeps giving me an error. import { BoxProps } from '@mui/material'; interface CustomProps { sx: BoxProps['sx&apo ...

Leveraging NgClass with observables

Wondering what the best practice is for handling observables in authentication. I have sections of my code where different content needs to be rendered based on whether the user is logged in or not. Currently, I am using "*ngIf="accountService.currentUser$ ...

The height of the ion-textarea in Ionic-angular reduces

I've been working on a project using the ionic-angular framework. I've encountered an issue where the height of the ion-textarea is sometimes decreased to 0px. The code for the textarea looks like this: <ion-textarea class="translated&quo ...

The JokesService (?) has encountered dependency resolution issues that Nest is unable to resolve

Currently delving into the world of NestJS and feeling a bit perplexed about the workings of "modules". In my project, I have two modules namely JokesModule and ChuckNorrisApiModule. My goal is to utilize the service provided by ChukNorrisService within th ...

How can I prevent users from using the inspect element feature in Angular 4?

I have a collection of elements that I need to selectively display on a webpage. To achieve this, I am utilizing the following code snippet: [style.display]="!student.selected?'none':'block'" However, upon inspecting the element, a ...

Getting environment variables on the client side in Next.js: A step-by-step guide

How can I retrieve an environment variable in my Next.js application and pass the data into datadogRum.init? // _app.tsx import React from "react"; import { useEffect } from "react"; import type { AppProps } from "next/app"; ...

What is the best way to ensure string comparison safety in Angular templates when dealing with null or undefined values?

Okay, so I encountered the following scenario: <span *ngIf="!someItem?.description==''"> The situation is: If someItem is defined and the description is not an empty string. Essentially, this can be interpreted as not equal to any value X ...