【发布时间】:2019-08-05 11:55:45
【问题描述】:
当我的 http 方法包含在我的组件中时,它会返回结果,但在从位于上一级目录的服务调用时不会返回任何结果。
我检查了控制台,没有错误。我尝试打印到控制台,该控制台在服务内工作(返回所需的数据),但在子组件内运行时不能。
这是我正在尝试构建的服务:
import { Injectable } from '@angular/core';
import { Resturant } from '../../models/resturant.model'
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class GetResturantsService {
fullListresturants: Resturant[];
constructor(private http:HttpClient) { }
fetchList(){
this.http.get('https://lunchlads.firebaseio.com/posts.json')
.pipe(map(responseData =>{
const postsArray: Resturant[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)){
postsArray.push({ ...responseData[key], id:key })
}
}
return postsArray;
}))
.subscribe(posts => {
// this.fullListresturants = posts;
});
}
}
这是目录下一个文件的组件:
import { Component, OnInit } from '@angular/core';
import { Resturant } from '../../../models/resturant.model'
import { GetResturantsService } from '../get-resturants.service'
import { HttpClient } from '@angular/common/http';
//import { map } from 'rxjs/operators';
@Component({
selector: 'app-list-all',
templateUrl: './list-all.component.html',
styleUrls: ['./list-all.component.css']
})
export class ListAllComponent implements OnInit {
fullListresturants: Resturant;
constructor(private http:HttpClient, private listAllResturants:GetResturantsService) { }
ngOnInit() {
this.onfullList();
}
onfullList(){
this.fullList();
}
private fullList(){
// this.http.get('https://lunchlads.firebaseio.com/posts.json')
// .pipe(map(responseData =>{
// const postsArray: Resturant[] = [];
// for (const key in responseData) {
// if (responseData.hasOwnProperty(key)){
// postsArray.push({ ...responseData[key], id:key })
// }
// }
// return postsArray;
// }))
// .subscribe(posts => {
// // this.fullListresturants = posts;
// });
this.listAllResturants.fetchList();
}
}
firebase 后端包含大约 10 条记录,其中包含 name:string、votes:number 和 selected:number 字段。从组件运行时,html 文件仅返回带有 *ngFor 循环的名称值。
从服务运行时,不会返回任何内容,并且控制台中不会报告任何错误。
我怀疑问题出在我如何从组件调用 fetchList 方法的某个地方,但我和 google 无法确定我做错了什么。
【问题讨论】:
标签: angular8