如何使用非迭代可观察数据服务

时间:2018-11-23 18:57:43

标签: service observable

我有一个可观察的数据服务,我想在我的角度页面上使用。我见过的大多数示例都返回一组数据,这些数据可以放在表或* ngFor循环中。但是,如果我只有一项数据并且不是迭代数据(它只是一个字段的对象)怎么办?如何将其注入页面?

页面看起来像这样:

<div [dataSource]=“source$”>
    {{ source$.data }}
</div>

ts文件看起来像这样:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { WatermelonService } from '../../../../providers/chat/watermelon.service';
import { Observable } from 'rxjs';

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

source$ : Promise<void | Observable<Object>>;

constructor(private _activatedRoute : ActivatedRoute,
private _watermelonService : WatermelonService) { }

ngOnInit() {
const watermelonId = this._activatedRoute.snapshot.paramMap.get('id');
this.source$ = this._watermelonService.getWatermelon(true, watermelonId);
}

}

WatermelonService看起来像这样:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpErrorResponse, HttpParams, HttpHeaders } from '@angular/common/http';
import { AuthService } from '../../core/auth.service';

@Injectable()
export class WatermelonService {


constructor(private http: HttpClient, public afAuth: AuthService) { }

getWatermelon(atb : boolean, watermelonId : string) {
const url = /* watermelonFunctions endpoint */
    
const options = /* options */
return this.http.get(url, options);
}
}

最后,在这里,firebase函数端点返回数据:

exports.getWatermelon = functions.https.onRequest((req, res) => {
db.doc(‘…’).get().then(watermelon => {
    res.status(200).send({data: watermelon.data});
});
}

0 个答案:

没有答案