I need to store the result of a function in my services into an array of objects in my TypeScript file.
getserver(id:number) {
const server = this.servers.find(
(s) => {
return s.id === id;
}
)
}
The return type of this function is void, but I want to store it as an object in my TypeScript file and I'm encountering an error:
*Error type void is not assignable to type {id:number,name:string,status:string}[];
My question is what am I doing wrong? Do I need to convert the void return type into an object somehow? If so, how can I do that?
edit-server.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ServerService } from '../../servers.service';
@Component({
selector: 'app-edit-server',
templateUrl: './edit-server.component.html',
styleUrls: ['./edit-server.component.css']
})
export class EditServerComponent implements OnInit {
servers!: {id:number,name:string,status:string}[];
constructor(private route: ActivatedRoute, private serviceserv: ServerService) { }
serverName = '';
serverStatus = '';
ngOnInit(): void {
this.servers= this.serviceserv.getserver(2);
}
onupdate() {
this.serviceserv.updateserver(this.servers.id, {name:this.serverName,status:this.serverStatus});
}
}
server.service.ts
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ServerService {
servers = [
{
id: 1,
name: 'ProductionServer',
status:'online'
},
{
id: 2,
name: 'TestServer',
status: 'online'
},
{
id: 3,
name: 'DevServer',
status: 'offline'
}
];
getservers() {
return this.servers;
}
getserver(id:number) {
const server = this.servers.find(
(s) => {
return s.id === id;
}
)
console.log(server!.id);
}
updateserver(id: number, serverInfo: { name: string, status: string }) {
const server = this.servers.find(
(s) => {
return s.id === id;
}
);
if (server) {
server.name = serverInfo.name;
server.status = serverInfo.status;
}
}
}