What are the steps to code this in Angular14 syntax?

Here's the code snippet:

constructor(obj?: any) {
    this.id = obj && obj.id || null;
    this.title = obj && obj.title || null;
    this.description = obj && obj.description || null;
    this.thumbnailUrl = obj && obj.thumbnailUrl || null;
    this.videoUrl = obj && obj.videoUrl ||
                         `https://www.youtube.com/watch?v=${this.id}`;
}

Unfortunately, this code doesn't seem to work in Angular 14.

I haven't attempted any troubleshooting yet.

Answer №1

In order to achieve your goal, it is advisable to refrain from using constructors in the manner you currently are. Instead, consider utilizing the constructor to inject services and providers. It appears that the task you are attempting to complete can be accomplished through ngOnInit and a method within the class. If there is a need for variables to be assigned prior to ngOnInit, you can still include code in the constructor, but initialization should not take place there. The key is to ensure that the variables are initialized before the constructor is executed.

Answer №2

To simplify the code, you can eliminate the need for obj &&

Here is an alternative approach:

constructor(obj: any = {}) {
  this.id = obj.id || null;
  this.title = obj.title || null;
  this.description = obj.description || null;
  this.thumbnailUrl = obj.thumbnailUrl || null;
  this.videoUrl = obj.videoUrl || `https://www.youtube.com/watch?v=${this.id}`;
}

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

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 ...

Serve both .ts and .js files to the browser using RequireJs

In my ASP.NET Core Project, the following files are present: greet.ts export class WelcomMesssage { name: string; constructor(name: string) { this.name = name; } say(): void { console.log("Welcome " + this.name); } } GreetExample.ts import * as ...

Utilizing MySQL Data in an Angular 2 Front-End Component within an Electron Desktop Application

Being new to Electron, this is my first attempt at creating a desktop app. One section of the application simply displays current forecasts based on customer data retrieved using standard database queries. I've opted to use a local MySQL database to ...

When a module is generated, it appends an additional slash to the path in the app.module.ts file

I've noticed a strange behavior with the generator in Angular CLI tools that adds an extra slash character for modules. For example, when running ng generate component visual a line like this is added to the app.module.ts file import { VisualCo ...

Configuring Typescript target and library to utilize Promise.allSettled on outdated web browsers

I am currently using TypeScript version 4.3.5 and Node.js version 14.18.1 in my project. The code I am working on is compiled to target both old and new browsers by setting target=es5 in the tsconfig file. I make use of both Promise.all and Promise.allSett ...

Enforce Immutable Return in TypeScript

Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time. For example, let's create an interface: interface freeze{ frozen: boolean; } Now, let's define a deep freeze function: f ...

Pass along a JSON array from Express to Angular2

I have been working on sending a custom array filled with mongoose errors, and I am successfully creating the array. Below is the code snippet: student.save(function(err, student) { if(err) var errors = []; for (field in err.errors) { ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

The process of setting up a dynamic cursor in ReactFlow with Liveblocks for precise zooming, panning, and compatibility with various screen resolutions

The challenge lies in accurately representing the live cursor's position on other users' screens, which is affected by differences in screen resolutions, zoom levels, and ReactFlow element positioning as a result of individual user interactions. ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Errors TS2585 and TS2304 encountered during compilation of TypeScript file using Axios

What steps should I take to fix the errors that arise when attempting to compile my TypeScript code using tsc index.ts? node_modules/axios/index.d.ts:75:3 - error TS1165: In an ambient context, a computed property name must reference an expression of lite ...

Is there a way to merge my local store with Firestore using ngrx entity?

Currently, I'm facing a challenge while using NgRx and Firestore as I attempt to keep the local store in sync with a firestore collection. I have set up an observable that triggers when the firestore collection is updated. However, in my reducer, I am ...

Accessing file uploads in Angular 2

<div class="fileUpload btn btn-primary"> <span>Select File</span> <input id="uploadBtn" type="file" class="upload" value="No File Chosen" #uploadBtn/> </div> <input id="uploadFile" placeholder="No File Selected" disable ...

Tips for sending data returned asynchronously from an Observable in Angular from a Child component to its Parent

I am facing a challenge passing Async data from child to parent component. When I try to access console.log(this.values) within the ngAfterViewInit() method in the parent component's HTML page load, it returns an empty value. However, upon clicking th ...

Choose everything except for the information determined by the search

Currently facing an issue with the select all functionality. I found a code snippet on this link but it's not exactly what I need. I want to modify the select all feature so that it is based on the search value. For instance, if I have a set of data ...

The HttpPut request code format is malfunctioning, although it is effective for another request

I'm struggling with a HTTPPUT request that just won't get called. Strangely enough, I have a similar put request that works perfectly fine for another tab even though both pages are practically identical. I've exhausted all options and can&a ...

Angular's GET HTTP request has resulted in a 500 error message, specifically the Internal Server Error

Attempting to send a GET request to the server where only authenticated users can access a specific route ("/user") after logging in. However, even after a successful login, users are unable to gain access to the "/user" route. A middleware function named ...

Angular Component Test Results in TypeError Error Failure

After defining a custom error class called CustomError: export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); } } I want to throw instances of ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Any ideas on troubleshooting the NG0100: ExpressionChangedAfterItHasBeenCheckedError issue and resolving it?

I have encountered NG0100: ExpressionChangedAfterItHasBeenCheckedError in Angular, and it seems to persist despite my efforts in my scenario. Essentially, within the interceptor, I have a service that loads a boolean value representing "status": interce ...