Error: Cannot access Angular 5 Title service at this time

When attempting to change the page title using BrowserModule, I encountered an issue. I added the BrowserModule and Title in the application module as shown here: https://angular.io/guide/set-document-title

However, in a child module where I tried to add the service and module (BrowserModule) as well, I faced a problem with the Title service being 'undefined'.

Here is the code for the module:

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { RouterModule, Routes } from "@angular/router";

import { ProductService } from "../../services/Product";

import { ProductComponent } from "../../components/product/component";
import { ProductResolve } from "../../components/product/resolve";

const routes: Routes =
[
    {
        path: "produs/:url",
        component: ProductComponent,
        resolve:
        {
            Product: ProductResolve,
        },
    },
];

@NgModule({
    imports:
    [
        CommonModule,
        RouterModule.forChild(routes),
    ],
    providers:
    [
        ProductResolve,
        ProductService,
    ],
    declarations:
    [
        ProductComponent,
    ],
    exports:
    [
        RouterModule,
        ProductComponent,
    ],
})
export class ProductModule { }

And here is the code for the component:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Product } from "../../services/Product";
import { Title } from '@angular/platform-browser';

@Component({
    templateUrl: "../../templates/product/component.html",
    styleUrls: [
        "../../sass/product/component.scss",
    ]
})

export class ProductComponent implements OnInit, OnDestroy
{
    private Subscribe: any;

    constructor(private titleService: Title, private Route: ActivatedRoute)
    {

    }

    ngOnInit()
    {
        this.Subscribe = this.Route.data.subscribe(this.process);
    }

    private process(product: Product)
    {
        //console.log(this.title);

        //this.titleService.setTitle(product.Title);
    }

    ngOnDestroy()
    {
        this.Subscribe.unsubscribe();
    }
}

Finally, here is the app module code snippet:

import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
...

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ...
        BrowserModule,

    ],
    providers: [LoadingScreenService, Title],
    bootstrap: [AppComponent],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppModule { }

Answer №1

One of the most common issues developers encounter is when a class method is utilized as a callback function, resulting in an incorrect reference to this within the method. The recommended solution is to replace the standard function with an arrow function for the callback:

this.Subscribe = this.Route.data.subscribe((product: Product) => {
    this.process(product);
});

Answer №2

It appears that you may be losing track of the context. When inside the process() function, the reference to this no longer points to the class instance.

One way to fix this issue is by using .bind(this).

this.Subscribe = this.Route.data.subscribe(this.process.bind(this));

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

Guide on accessing a modal component in Angular?

I have an Edit Button on my component called SearchComponent. When the user clicks this button, it currently redirects them to another component named EditFormComponent using navigateByUrl('url-link'). However, I would like to enhance the user ex ...

Is Angular 5 ngx-permissions causing permissions to be deleted upon page refresh? Learn how to prevent this issue

https://i.stack.imgur.com/P1dr1.png https://i.stack.imgur.com/ktmB3.png Permissions Disappear after Page Refresh Is there a way to prevent permissions from being deleted upon refresh? ...

"Learn the process of integrating Javascript files from the Angular assets folder into a specific Angular component or module (such as Angular 2, 4,

I have custom1.js, custom2.js, and custom3.js JavaScript files that I need to load into Angular components component1, component2, and component3 respectively. Instead of adding these files to the index.html globally, I want to load them specifically for e ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Error: "Access-Control-Allow-Origin" header is missing in Firebase Function

I have encountered an issue with my firebase functions GET request. While I am able to receive data using Postman, I am facing difficulties when trying to fetch data from my front-end application. Upon accessing the endpoints, I am seeing the following er ...

Issue encountered when attempting to assign `fontWeight` within `makeStyles` using `theme` in Typescript: Error message states that the property is not

Currently, within my NextJS project and utilizing MUI, I am attempting to define a fontWeight property using the theme settings in the makeStyles function. Oddly enough, this issue only arises when building inside a docker container, as building locally po ...

What is the best way to retrieve HTML content using an Angular method?

Okay, so the title might not be the greatest...but I couldn't think of anything better: I want to emphasize search keywords in the result list...that's why I'm having trouble with this problem. CSS: .highlightText{ font-weight: bold; } In ...

Sending detailed exception information from asp.net core to the client (such as Angular)

Trying to retrieve exception text from the backend (ASP.NET Core) in an Angular application has been a challenge. Examples have shown the controller action's return type as either JsonResult or ActionResult. In such cases, we can utilize the followi ...

Forever waiting: Angular HTTP requests stuck in limbo

Switching from MongoDB to MySQL for my Angular/NodeJS project has brought about some challenges, particularly with handling HTTP Requests. I have tried GET and POST requests, but GET always remains pending and eventually fails, while POST does not successf ...

Angular Ahead-of-Time (AOT) compilation causes multiple route definitions to be

Having a bit of trouble configuring ahead-of-time compilation for my lazy-loaded Angular app. The lazy-loaded routes are specified in the app.routes.ts file, which is imported by app.module.ts. Running ngc results in the content of app.routes.ts being mer ...

The attribute 'elements' is not present within the data type 'Chart'

var canvas = document.getElementById("canvas"); var tooltipCanvas = document.getElementById("tooltip-canvas"); var gradientBlue = canvas.getContext('2d').createLinearGradient(0, 0, 0, 150); gradientBlue.addColorStop(0, '#5555FF'); grad ...

The Angular project I am hosting on GitHub Pages seems to be having trouble locating its files, leading to a

After successfully building an Angular project using the ng build command, I ran into an issue when uploading it to a GitHub repository and creating its GitHub Page. Despite working perfectly locally, none of the bundle files could be found when accessing ...

Using React with Typescript: Passing Props and Defining Data Types

As a relatively new TypeScript enthusiast, I find myself facing some challenges. Specifically, I am struggling with errors in my code and uncertain about how to properly pass props and select the correct type. Any guidance on this matter would be greatly a ...

Tips for managing variables to display or hide in various components using Angular

In this example, there are 3 main components: The first component is A.component.ts: This is the parent component where an HTTP call is made to retrieve a response. const res = this.http.post("https://api.com/abcde", { test: true, }); res.subscribe((r ...

Angular validation for password and confirmation password fields

I have been working on implementing password and confirm password validation within an angular project. I recently came across a helpful answer on this thread Confirm password validation in Angular 6 that I tried to follow. Unfortunately, I am encountering ...

How can I access a file uploaded using dxFileUploader?

I am facing an issue with retrieving a file from dxFileUploader (DevExpress) and not being able to read it in the code behind. The file is only appearing as an object. Here is My FileUploader : { location: "before", ...

Testing TypeScript functionality within the Eclipse environment with unit tests

Is there a method to test TypeScript code on the Eclipse platform? I'm searching for something similar to JUnit, but most of the tools I've come across are geared towards Visual Studio. ...

Two distinct arrays interacting and syncing with each other through a single API request

I find myself in a strange situation. I am dealing with two objects: sessionBase: ISessionViewWrapperModel = <ISessionViewWrapperModel>{}; sessionDisplay: ISessionViewWrapperModel = <ISessionViewWrapperModel>{}; After making an api call, both ...

The filtering feature in the Row Group table of PrimeNG controls is malfunctioning and causing issues with the Dropdown

Within my Angular project, I have integrated PrimeNG controls version 11.4.4. Utilizing the Table control, I've structured tabular data to display rows in a grouped fashion with collapsible functionality. I've recently introduced a textbox and d ...

The 'flatMap' property is not found on the 'string[]' data type. This issue is not related to ES2019

A StackBlitz example that I have set up is failing to compile due to the usage of flatMap. The error message reads: Property 'flatMap' does not exist on type 'string[]'. Do you need to change your target library? Try changing the ' ...