Home > database >  How to solve TypeError (Cannot set properties of undefined) when assigning a service variable
How to solve TypeError (Cannot set properties of undefined) when assigning a service variable

Time:02-13

What I'm trying to do is assigning the value of a select form (dropdown) to a variable in a service, because I need this variable across components.

dropdown.component.html:

<mat-form-field>
<mat-select [(ngModel)]="selectedValue"  (ngModelChange)='onChange()' placeholder="select ticker">
    <mat-option *ngFor="let t of tickers" [value]="t">{{t}}</mat-option>
</mat-select>
</mat-form-field>

dropdown.component.ts:

import { Component, OnInit } from '@angular/core';
import {LoadDfParamsService} from '../../services/load-df-params.service';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {

  tickers = ["BTC-PERP", "ETH-PERP", "ATOM-PERP"];

  public selectedValue!:string;
  private DfParams!: LoadDfParamsService;

  constructor() { }

  ngOnInit(): void {
  }
  onChange() {
    this.DfParams.ticker = this.selectedValue;
    //console.log(this.DfParams)
  }
}

LoadDfParamsService:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LoadDfParamsService {

  public ticker!: string;

  constructor() { }
}

The variable selectedValue will be updated succesful in dropdown.component.ts
But by trying to assign the variable of the service

this.DfParams.ticker = this.selectedValue;

I get this error:

core.mjs:6485 ERROR TypeError: Cannot set properties of undefined (setting 'ticker')
    at DropdownComponent.onChange (dropdown.component.ts:21:25)
    at DropdownComponent_Template_mat_select_ngModelChange_1_listener (dropdown.component.html:2:59)
    at executeListenerWithErrorHandling (core.mjs

How can I solve this?

CodePudding user response:

Since angular is using dependency injection, you need to inject the service through the constructor or the setters.

Example injecting the service in the constructor

import { Component, OnInit } from '@angular/core';
import {LoadDfParamsService} from '../../services/load-df-params.service';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {

  tickers = ["BTC-PERP", "ETH-PERP", "ATOM-PERP"];

  public selectedValue!:string;

  constructor(private DfParams: LoadDfParamsService) { }

  ngOnInit(): void {
  }
  onChange() {
    this.DfParams.ticker = this.selectedValue;
    //console.log(this.DfParams)
  }
}

Looking forward to hearing back from you on whether this resolved the issue

CodePudding user response:

Just inject the service into the constructor

constructor(private DfParams: LoadDfParamsService) { }
  • Related