1

I am trying to load the data for places before the component renders.

dashboard.html

{{ places[0]._id }} //just for testing

dashboard.ts

import { Component, OnInit } from '@angular/core';
import { PlacesService } from 'src/app/services/places/places.service';
import { IPlace } from 'src/app/types/places';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss'],
})
export class DashboardComponent {
  places: IPlace[] = [];
  
  constructor(
    private placesService: PlacesService,
    private route: ActivatedRoute,
  ) {
    
  }
  ngOnInit(): void {
    this.route.data.subscribe((data) => {
      this.places = data['places'];
    });
  }

}

places.resolver.ts

import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  ResolveFn,
  RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { PlacesService } from '../services/places/places.service';

import { IPlace } from '../types/places';

@Injectable({
  providedIn: 'root',
})
export class PlacesResolver {
  constructor(private placesService: PlacesService) {}

  resolve: ResolveFn<IPlace[]> = (
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<IPlace[]> => {
    return this.placesService.getPlaces();
  };
}

places.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable, pipe } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable({
  providedIn: 'root',
})
export class PlacesService {
  constructor(private http: HttpClient) {}

  getPlaces(): Observable<any> {
    var requestUrl = `/api/places`;

    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
    });
    return this.http.get(requestUrl, {
      headers: headers,
    });
  }
}

app-routing.module.ts

import { NgModule } from '@angular/core';
import { ActivatedRouteSnapshot, RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { DashboardComponent } from './pages/dashboard/dashboard.component';
import { PlacesResolver } from './resolvers/places.resolver';
import { AuthGuard } from './_helpers/authGuard/auth.guard';

const routes: Routes = [
  { path: '', component: HomeComponent },
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard],
    resolve: {
      places: PlacesResolver,
    },
    data: { role: [] },
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

I have a button to route to /dashboard: navbar.html

<button
    label="Dashboard"
    (click)="dashboardClick()"
    *ngIf="
      (null | isLoggedIn | async) && (['admin', 'worker'] | hasRole | async)
    "
  >
    Dashboard
  </button>

navbar.ts

there are 2 different types of dashboards in this case url will be ''

dashboardClick() {
    this.url = this.lastVisitedService.getLastVisited()?.split('/')[2] || '';

    this.router.navigate(['/dashboard', this.url]);
  }

When I click the dashboard button the _id is not displayed but I do get the console.log(result) back with the data. When I refresh the page I get the data logged again but now the data is displayed on the page as well. what am I doing wrong? Is there another way to do it? I do have an interceptor set up but I don't think that that's the problem, if you need it just ask.

  • I don't see where `dashboard.ts` has `this.route`. I would have expected to see `private route: ActivatedRoute` in that constructor. – possum Mar 29 '23 at 10:25
  • sorry, I deleted a few things from what I uploaded so it's not cramped. Didn't mean to remove that. @possum – aron bleier Mar 29 '23 at 10:35

1 Answers1

0

Well, I fixed it.

I don't know why or how this works but this.router.navigate(['/dashboard', this.url]); goes to route .../dashboard/ and this route is not correct so I have to remove the url from the navigate array when it is empty so it navigates to .../dashboard

this is my new method for clicking the dashboard button

dashboardClick() {
    this.url = this.lastVisitedService.getLastVisited()?.split('/')[2] || '';
    if (this.url) this.router.navigate(['/dashboard', this.url]);
    if (!this.url) this.router.navigate(['/dashboard']);
  }