Search code examples
angulartypescriptservicevoid

Angular Services - Type 'void' is not assignable to type 'Project[]'


im struggeling with using a service in Angular.

I have the service:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Project } from '../project';
import { Observable, of } from 'rxjs';

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

  constructor(
    private http: HttpClient,
  ) { }



  getProjects() {

    this.http.get<Project[]>('/api/getprojects').subscribe((response) => {
      console.log(response);
      return response;
    })

  }
}

I use the service in the component Dashboard:

import { ThrowStmt } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
import { Project } from '../project';
import { ProjectService } from '../service/project.service';

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

  constructor(
    private projectService: ProjectService
  ) { }

  projects!: Project[];

  ngOnInit():void {
    this.getProjects();
  }

  getProjects(){
    this.projects = this.projectService.getProjects();
    return this.projects;
  }



}

But get this error:

Type 'void' is not assignable to type 'Project[]'.

27     this.projects = this.projectService.getProjects();

I tried some things and already noticed the Angular Tutorial of Heros, but was not able to solve it. May you help me?


Solution

  • ProjectService (do not subscribe in your services)

     getProjects() {
        return this.http.get<Project[]>('/api/getprojects')
    }
    

    DashboardComponent

    projects$ = this.projectService.getProjects();

    And in your template you subscribe to the projects$ observable for example projects$|async

    <div *ngFor="let project of projects$ | async)">{{project|json}}</div>