I'm seeing an issue where my SafeResourceUrl is being displayed as undefined within a function of the identical class

export class ClassName implements OnInit {

    url: string = "{{'content.url' | translate}}";
    urlSafe: SafeResourceUrl;

    constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { }

    ngOnInit() {
        this.translate.stream('content.url').subscribe((text: string) => {
            this.urlSafe = this.sanitizer.bypassSecurityTrustResourceUrl(text);    

            console.log(this.urlSafe);//logs the SafeResourceUrl Object

            this.runSpecificFunction();
        });

        
    }

    runSpecificFunction() {

        console.log(this.urlSafe); //undefined

    }    
}

Why is it that in the ngOnInit method of this class, I can log the SafeResouorceUrl object successfully?

However, I am encountering difficulties accessing the URL from that object in the runSpecificFunction method below.

Although the code within runSpecificFunction could be executed within ngOnInit, it needs to be structured this way for a specific purpose. Unfortunately, I cannot understand why I am getting undefined.

Can someone please point out what I might be doing wrong in this Angular class? As a new learner, I appreciate any guidance and support provided!

Answer №1

If you format your code in the following way, it will store your value and still function correctly.

export class ClassName implements OnInit {

    url: string = "{{'content.url' | translate}}";
    urlSafe: SafeResourceUrl;

    constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { }

    ngOnInit() {
        this.translate.stream('content.url').subscribe((text: string) => {
            this.DoAThing(text);
        });
    }

    DoAThing(url) {
        this.urlSafe = this.sanitizer.bypassSecurityTrustResourceUrl(url);    
        console.log(this.urlSafe);//displays the SafeResourceUrl Object
    }    
}

Answer №2

Here is the function you provided:

PerformAction() {

    console.log(this.urlSafe); //undefined

}    

This function is not connected to this. To execute it, you need to call someSafetyUrl.PerformAction.

Another option is to use an arrow function:

PerformAction = () => {

    console.log(this.urlSafe); // this will always be connected 

}    

More Information

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

What is the process for including an "everything" alternative on a dropdown menu?

Need assistance with my dropdown component that filters a list based on 'state' data. Below is the HTML code for the dropdown: <section class="select-wrapper {{wrapperClass}}" [ngClass]="{'expanded': toggle}" (click)="toggleSelect($ ...

Angular Form Template Unidirectional Data Binding Example

I'm facing a challenge with one-way binding to a default value in my HTML form. Within my component, I have a Connection string that is initially set from local storage: export class AuthAdminComponent implements OnInit { public authenticated = f ...

What is the method for inserting two dashes within a number?

For the output, I am looking to showcase a number in the following format => 979-9638403-03. At present, the number appears like this => 979963840303. portfolio.ts export class Portfolio { ... DEPO: number; /* DEPO */ const ...

I'm having trouble establishing a connection with the Appwrite platform

Encountered an issue while trying to connect to appwrite. The specific error message is: Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL at Account.<anonymous> (appwrite.js?v=d683b3eb:932:19) at Generator.nex ...

Display JSON data in Angular view by extracting the desired value

Hey there! I have a GET response data with a field like "DeletionDate": "0001-01-01T00:00:00". What I'm trying to achieve is to remove the time part T00:00:00 and only display half of the value in my views. Is there a way to trim the value and show it ...

Incorporate a Custom Icon into NbSelect

I am currently utilizing Nebular in a project, where multiple dropdowns are being used as shown below: <nb-select fullWidth placeholder="Office" formControlName="office"> <nb-option value="Office_A"&bt;Office A</n ...

A versatile sorting algorithm

Currently, I am working on converting the material UI sorting feature into a generic type. This will enable me to utilize it across various tables. However, I have hit a roadblock in implementing the stableSort function, which relies on the getSorting func ...

Unusual behavior when importing in Angular 2 using TypeScript

While working on a demo for another question on Stack Overflow, I initially used angular-cli and then switched to Plunker. I noticed a peculiar difference in behavior with the import statement between the two setups. The issue arises with the second impo ...

Discover the Prisma findMany method for implementing tanstack react table functionality

I'm looking to build a table (using tanstack table) populated with data fetched from Prisma.findMany. Let's suppose I have a User model: model User { id Int @id @default(autoincrement()) name String age String email String } Now, in my p ...

Encountering the error message "Unable to access properties of null (specifically 'useState')" while trying to utilize a component from my custom library

After developing a personalized UI library and style guide to standardize components in my application, all was running smoothly until I incorporated a component utilizing the useState hook. An error consistently surfaces whenever I attempt to use a compo ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Is it possible for Go's http server to compile TypeScript?

My current setup involves a NodeJS Application that launches an http server and utilizes client side code written in TypeScript with Angular 2. I'm curious if it's possible to achieve the same functionality using Go programming language? I trie ...

Can InstanceType<T> be utilized with an abstract class?

My intention is to enable it to reference implementations rather than the abstract itself, all while exclusively depending on the definitions in the abstract interface. ...

Set up Nginx to host Angular static files and act as a reverse proxy for express

Recently, I've started using Nginx for serving static Angular files and proxying to a backend Express server. Both the frontend (with Nginx) and backend are dockerized. My frontend consists of a button that makes a request to fetch data from Express. ...

Ways to distinguish a type that may not have a defined value

What is the most effective method to define an interface that may be undefined? Currently, I have the following setup but I am seeking a more sophisticated and succinct alternative. interface RouteInterface { path: string; test: boolean; } type TypeOr ...

The ngOnChanges() function fails to detect changes in the boolean @Input value coming from the parent component

Whenever I try to pass a dropdown toggle value to a child component, it works fine when the toggle is true but not when it's false. Despite using ngOnChanges to detect changes, it only picks up on the true values. ChildComponent export class ChildCom ...

Choose the appropriate data type for the class variable (for example, fArr = Uint32Array)

const functionArray: Function = Uint32Array; new fArr(5); The code snippet above is functioning properly. However, TypeScript is throwing a TS2351 error: "This expression is not constructable. Type 'Function' has no construct signatures". I wo ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cas ...

Ways to resolve the error 'Node Sass unable to locate a binding in your current environment' while executing npm run build

When executing sudo npm run build, I encountered an error stating that it cannot find the binding for sass. My npm version is currently 11.13.0 and I have only one version installed. I have tried various solutions such as npm install node-sass, npm rebui ...