Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times.

However, no matter what I try, the data received through this.route.data.subscribe is always undefined. I have confirmed that the service is indeed receiving a response from the server. Strangely, everything works fine when I use the service directly.

The component responsible for processing the data:

import { Component, OnInit, Input } from '@angular/core';
import { TempsService, Temps } from '../../temps.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-temps',
  templateUrl: './temps.component.html',
  styleUrls: ['./temps.component.scss']
})
export class TempsComponent implements OnInit {
  @Input() solar: boolean;
  solarURL: string = 'tempSolar';
  waterURL: string = 'tempWater';
  tempSolar: number;
  tempWater: number;
  timestamp: string;

  temps: Temps;

  constructor(private route: ActivatedRoute,
  private tempService: TempsService) { }

  showWaterTemp() {
    this.tempService.getTemp(this.waterURL)
      .subscribe(data => {
        this.tempWater = data.rawValue;
        this.timestamp = data.time;
      });
  }

  showSolarTemp() {
    this.route.data
      .subscribe(data => {
        this.tempSolar = data.rawValue;
      });
  }
  ngOnInit() {
    if (this.solar) {
      this.showSolarTemp();
      this.showWaterTemp();
    }
  }
}

This is the routing module (I am using the NowUI Angular theme by CreativeTim, so most things were done by them):

import { Routes } from '@angular/router';

import { DashboardComponent } from '../../dashboard/dashboard.component';
import { UserProfileComponent } from '../../user-profile/user-profile.component';
import { TableListComponent } from '../../table-list/table-list.component';
import { TypographyComponent } from '../../typography/typography.component';
import { IconsComponent } from '../../icons/icons.component';
import { MapsComponent } from '../../maps/maps.component';
import { NotificationsComponent } from '../../notifications/notifications.component';
import { TempsComponent } from '../../dashboard/temps/temps.component';
import { TempResolver } from '../../temp-resolver/temp-resolver.resolver';

export const AdminLayoutRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent, children: [
{ path: '', component: TempsComponent, resolve: { temps: TempResolver } }
] },
{ path: 'user-profile', component: UserProfileComponent },
{ path: 'table-list', component: TableListComponent },
{ path: 'typography', component: TypographyComponent },
{ path: 'icons', component: IconsComponent },
{ path: 'maps', component: MapsComponent },
{ path: 'notifications', component: NotificationsComponent }
];

And here is how the resolver is structured:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Temps, TempsService } from '../temps.service';
import { Observable } from 'rxjs/internal/Observable';

@Injectable()
export class TempResolver implements Resolve<Temps> {

test: number;
constructor(private tempService: TempsService) { }

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Temps> {
this.tempService.getTemp('tempSolar').subscribe(data => {this.test = data.rawValue})
alert(this.test)

return this.tempService.getTemp('tempSolar');
}
}

In conclusion, this issue presents an unusual challenge.

UPDATE: This is the service used for fetching the data:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TempsComponent } from './dashboard/temps/temps.component'

export interface Temps {
id: string;
time: string;
date: string;
name: string;
rawValue: number;
}

@Injectable()
export class TempsService {

constructor(private http: HttpClient) { }

url: string = window.location.hostname;

tempUrl = 'http://' + this.url + ':3000/latestTime/';

getTemp(temp: String) {
return this.http.get<Temps>(this.tempUrl + temp);
}
}

Answer №1

After incorporating the resolve feature into the dashboard component where the Temp component is utilized, the functionality has dramatically improved. The updated code now appears as follows:

{ path: 'dashboard',      component: DashboardComponent, resolve: {temps: TempResolver} }

instead of the previous version which looked like this:

{ path: 'dashboard',      component: DashboardComponent,
    children: [{ path: '', component: TempsComponent, resolve: { temps: TempResolver } }] 
},

Answer №2

Could you give this a shot?

this.route.data
  .subscribe(({temps}) => {
    this.tempSolar = temps;
  });

Answer №3

To avoid issues, it is recommended not to subscribe to fetchData() within the resolve() method; instead, directly return an Observable<data>. It's important to consider the asynchronous behavior of fetchData(). Calling alert(this.example) will often occur before fetchData() finishes executing, leading to a high chance of receiving an undefined value at that point.

You can simply modify the code to return getData() as an Observable<DataResponse>:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { DataResponse, DataService } from '../data.service';
import { Observable } from 'rxjs';

@Injectable()
export class DataResolver implements Resolve<DataResponse> {
  constructor(private dataService: DataService) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<DataResponse> {
    return this.dataService.getData('exampleData');
  }
}

Then, in the component, access the contentValue property when needed:

showDataContent() {
  this.route.data.subscribe((data: { content: DataResponse }) => {
    this.exampleData = data.content.contentValue;
  });
}

Feel free to check out the live demo on StackBlitz for a demonstration.

I hope this clarification helps you understand the process better!

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

When sending strings through an ajax call, spaces are getting converted to "'+'"

In my attempt to utilize AJAX for sending a POST request with multiple strings as parameters, I encountered an issue. The strings I am sending sometimes contain spaces. However, upon receiving the POST on the C# server side, I noticed that the string com ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Error: The function 'stepUp' was invoked on an object lacking the HTMLInputElement interface during an AJAX request

It's always frustrating to have to ask a question that has already been asked, but I'm having trouble finding a solution that works for me. My issue involves retrieving the value of an input and sending it via AJAX. $("#cell_number").on("change" ...

Issue when calling .create() method on Mongoose schema: "this expression is not callable" error in TypeScript

Encountering an error with the .create method on a mongoose model in Next JS while making a call in an API route. The get request is functioning properly... The structure: pages>API>task.tsx import dbConnect from "../../util/dbconnect"; im ...

Injecting components into the DOM using JavaScript in Vue.js

I am currently developing a GUI for a webgame using Vue.JS and opting to use http-vue-loader instead of Webpack or similar tools. Personally, I find them cumbersome and prefer to avoid using them. Typically, in order to integrate my components into the DO ...

Ways to exit a forEach loop when a specific condition is satisfied and obtain a string or break statement

I'm currently using Angular 14 and have been encountering some issues with a piece of code involving a ternary operator. Despite researching resources like this one and others, I haven't found a solution that works for me. The code in question lo ...

To close the responsive menu, simply click anywhere outside of the navigation bar

My issue involves a responsive menu with Bootstrap. On desktop, the menu closes fine; however, on the responsive view, I want it to close when clicking outside of the nav menu in any area. Here is my navigation code: <!-- Navigation --> <nav id= ...

Can an XSS attack occur on a style tag with inline styling?

For example: <!DOCTYPE html> <html lang="en"> <head> <title>Test for Potential XSS Attack</title> <style> div { background-color:blue; height:120px; ...

Choose the initial unordered list within a specific division through Jquery

In a div, there is a ul. Inside a li, there is another ul. The task is to select only the first ul inside the div using jQuery. The HTML markup: <div class="parent"> <div class="clearfix"> <div class="another-div"> <ul cl ...

React: Issue with function not recognizing changes in global variable

When the run button is clicked, it triggers an event. However, clicking on the skip button does not take me to Switch Case 2 as expected. Even though the skip state updates, the function still outputs the old value of skip. const CustomComponent = () => ...

Oh no! "The accuracy of your BMI calculation is in question."

I am currently working on a technical assessment for a BMI calculator, but I am facing a challenge in implementing the formula. The instructions for calculating BMI are as follows: Step 1: The user's height is given in feet, so it needs to be conver ...

What is the method for obtaining the number of weeks since the epoch? Is it possible to

Currently, I am setting up a DynamoDb store for weekly reporting. My idea is to use the week number since 1970 as a unique identifier for each report record, similar to epoch milliseconds. Here are some questions I have: How can I determine the current w ...

Cannot access Nextjs Query Parameters props within the componentDidMount() lifecycle method

I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...

When attempting to select dates from the picker options, the array is found to be devoid of any entries

My challenge lies in working with an array of dates retrieved from the server to determine which dates should be disabled on the datepicker. getStaffAvailability(){ let x = this; this.$http.get(this.weeklyAvailabilityUrl + "GetAv ...

The functionality of Nuxt's asyncData is restricted when attempting to access data from authorized express routes

Setting up an online store. I began with the products, which can be pulled without authorization but require it for editing. The process is smooth so far, probably because it's happening on the client side where authentication information is included ...

Issue: ray.intersectScene does not exist as a function

For my basic WebGL project, I have been utilizing the sim.js code and its components. Recently, when I attempted to use the frustum class (refer to this question), it required updating my three.js. Unfortunately, this caused an issue: TypeError: ray.inter ...

Execute a JavaScript function daily for each new user

Can someone help me understand how to execute a JavaScript/jQuery function that triggers a PopUp once for each new user visiting a webpage? Below is the code I need assistance with. $(window).load(function() { $('#index9').fadeIn("slow"); ...

Is it possible to direct users to varying links based on their individual status?

import React from "react"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import Link from "next/link"; import { cn } from "@/lib/utils"; import { FaCircleChec ...

A guide on displaying a dynamically generated HTML string as HTML within an Angular 6 framework

I'm having trouble displaying Dynamic HTML (dropdowns) created with TypeScript. When I attempt to show it using innerHTML, the options appear as text instead of a dropdown menu. {{question.question}} <div [innerHTML]="question.question" c ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...