我正在努力在 Angular 中使用服務。
我有這樣的服務:
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;
})
}
}
我在組件儀表板中使用該服務:
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;
}
}
但是得到這個錯誤:
Type 'void' is not assignable to type 'Project[]'.
27 this.projects = this.projectService.getProjects();
我嘗試了一些東西并且已經注意到英雄的Angular Tutorial,但無法解決它。你能幫我嗎?
uj5u.com熱心網友回復:
ProjectService(不要訂閱您的服務)
getProjects() {
return this.http.get<Project[]>('/api/getprojects')
}
儀表板組件
專案$ = this.projectService.getProjects();
在你的模板中你訂閱了 projects$ observable 例如 projects$|async
<div *ngFor="let project of projects$ | async)">{{project|json}}</div>
uj5u.com熱心網友回復:
我不確定我是否正確,但它有效:) 目前儀表板組件看起來像這樣
export class DashboardComponent implements OnInit {
constructor(
private projectService: ProjectService,
) { }
projects!: Project[];
public projects$ = this.projectService.getProjects();
ngOnInit():void {
}
getProjects(){
//this.projects = this.projectService.getProjects();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/317150.html
下一篇:替換對按鍵事件不起作用的符號
