Trying to pass values from one component to another, but encountering issues with the code. The values are showing as undefined
on the next page.
Below is the code for my service class named UtilityService.ts
:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UtilityService {
constructor() { }
private message: string;
public setMessage(message): void {
this.message = message;
}
public readMessage(): string {
return this.message;
}
}
Here is the code for my first component:
import { Component, OnInit } from '@angular/core';
import { UtilityService } from '../UtilityService';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css'],
providers: [UtilityService]
})
export class ProductsComponent implements OnInit {
private service;
constructor(private employeeService: ProductService, utilityService: UtilityService) {
this.service = utilityService;
this.sendMessage();
}
private sendMessage(): void {
this.service.setMessage("How are you?");
}
}
Below is the code for my second component:
import { Component } from '@angular/core';
import { UtilityService } from '../UtilityService';
@Component({
selector: 'app-device-list',
templateUrl: './device-list.component.html',
styleUrls: ['./device-list.component.css'],
providers: [UtilityService]
})
export class DeviceListComponent implements OnInit {
private service;
private message: string;
constructor(
utilityService: UtilityService,
private restApi: ProductService,
private route: ActivatedRoute
){
this.service = utilityService;
this.readMessage();
}
private readMessage(): void {
this.message = this.service.readMessage();
console.log("Service message: " + this.message);
}
}
Following an article on passing data from parent to child component in Angular, but the console.log
shows undefined
.