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

In response to resolving an HTTP header issue with a status of 200 ok during API testing with Postman, what steps can be taken

Hello everyone, I am new to the world of Angular and facing some issues while learning. Following a tutorial on YouTube, I tried to replicate the process with a few modifications. Initially, my get API worked fine when tested with Postman, and the post API ...

I am currently working on an Angular 8 project and experiencing difficulties with displaying a specific value from a JSON object in my template using an ngFor loop

Apologies if I am not familiar with all the terms, as I am mostly self-taught. I started with Udemy and then turned to Stack Overflow to tackle the more challenging aspects. This platform has been incredibly valuable and I am truly grateful for it. Now, l ...

When attempting to play a YouTube video, Video.js throws an error stating that the identifier "youtube" is undefined

@Component({ selector: 'invidz-video-js-component', template: ` <div id="full-background"> <video id="vid" class="video-js vjs-default-skin vjs-fullscreen vjs-big-play-centered" controls data-setup='{ "techOrder" ...

Understanding DefinitelyTyped: Deciphering the explanation behind 'export = _;'

Having trouble integrating angular-material with an ng-metadata project and encountering some issues. Utilizing DefinitelyTyped for angular material, the initial lines are as follows: declare module 'angular-material' { var _: string; expo ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navigating to a new one. This projec ...

Deployment of a NextJS14 app to Vercel encountered an issue: Unexpected token '<' found in JSON at position 0

Here is the issue at hand: next: 14.1.4 next-auth: 4.24.7 node version: 20 This is the structure of my authentication folder: No errors occur when running npm run dev I've been investigating this issue for three days, but I am still stuck. I belie ...

Implementing a click event on an image in an Angular 4 application

I'm facing an issue with adding a click event to an image within an Angular component. I have tried the following code: <img src="../../assets/add.svg" width="18" height="18" (click)="addItem()"> However, this approach does not seem to work as ...

Failed deployment of a Node.js and Express app with TypeScript on Vercel due to errors

I'm having trouble deploying a Nodejs, Express.js with Typescript app on Vercel. Every time I try, I get an error message saying "404: NOT_FOUND". My index.ts file is located inside my src folder. Can anyone guide me on the correct way to deploy this? ...

Images in the Ionic app are failing to display certain asset files

Currently, I am working on an Ionic 4 app for both Android and iOS platforms. The issue I am facing is that only SVG format images are displaying in the slide menu, even though I have images in both SVG and PNG formats. public appPages = [ { ...

I noticed that when using Next.js with the `revalidate: 1` option on a static page, it is triggering two full F5 refresh actions instead of just one. I was hoping for

Currently, I have set up a blog post edit page in my Next.js project. The post pages are utilizing the Incremental Static Regeneration feature with a revalidation time of 1 second for testing purposes. In the future, I plan to increase this to a revalidat ...

Issue with rendering Base64 image array strings in FlatList component in React Native

In my RN App, I am trying to display a FlatList with Image Items but it seems like I have missed something. I am retrieving blob data from my API, converting it to a String using Buffer, and then adding it to an Array. This Array is used to populate the F ...

How can I receive the response from a GET request using React Query? I am currently only able to get the response

I have created a search component where I input a name in the request, receive a response, and display it immediately. However, after the first input submit, I get undefined in response. Only after the second submit do I get the desired response. The tec ...

Jest encounters issues while attempting to execute TypeScript test cases

Encountering an error while trying to execute tests in a repository that has a dual client / server setup. The error seems persistent and I'm unable to move past it. > jest --debug { "configs": [ { "automock": false, ...

Issue with Angular httpClient not correctly handling PHP error objects

My current task involves integrating with an older php login api that returns a success or error message response object. After connecting with the correct credentials, I receive the success object. However, if the credentials are incorrect, I receive the ...

Jsx Component fails to display following conditional evaluations

One issue I am facing is having two separate redux stores: items (Items Store) quotationItems (Quote Items). Whenever a product item is added to quotationItems, I want to display <RedButton title="Remove" />. If the quotationItems store i ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...

Agents should only be initialized within a before function or a spec in Angular

Having trouble with my private function: private GetChargesByClient(clientId: number): Observable<any[]> { const ds = new Date(); const dateTocompare = new Date(ds.setFullYear(ds.getFullYear() - 1)); return this.getCharges(id).pipe(map(res => re ...