So I'm intending to let NG to deal with subscription during the lifecycle of a component, let it auto-subscribe/unsubscribe.
Here is my service providing observable for calls to endpoint outside, MySvc.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpHeaders, HttpErrorResponse } from "@angular/common/http";
import { Observable, throwError } from 'rxjs';
const url = '...';
@Injectable()
export class MySvc{
constructor(private http: HttpClient) { }
getAllRec()
{
return this.http.get(url).pipe(map((res: Response) => res.json()));
}
myRec.ts
export interface myRec
{
name: string;
}
My display component MyPage.ts
import { Component, OnInit } from '@angular/core';
import { MySvc } from '..MySvc.service';
import { Observable, of} from "rxjs";
import { myRec} from '../models/myRec';
@Component({...})
export class MyPage implements OnInit {
public allRec$: Observable<myRec[]>;
constructor(private MySvc: MySvc) {}
ngOnInit()
{
this.allRec$ = this.MySvc.getAllRec(); // see compiling error below
}
Type 'Observable<Promise>' is not assignable to type
'Observable<myRec[]>'. Type 'Promise' is missing the following
properties from type 'myRec[]': length, pop, push, concat, and 26 more
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…