gpt4 book ai didi

angular - 将数据从 service.ts 传输到组件

转载 作者:太空狗 更新时间:2023-10-29 19:29:36 25 4
gpt4 key购买 nike

我真的被这个问题困住了,希望能在这里得到一些帮助。

基本上,我在 http.service 中做一个简单的 get http 请求,然后将 json 对象传输到 filter.service。之后我想将输出数组携带到组件中。但是我得到一个空错误。

http.service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class HttpService {

constructor(private http : Http) { }

getData() {
return this.http.get('https://angular2-49133.firebaseio.com/catalog.json')
.map((response : Response) => response.json());
}

}

过滤服务

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';

@Injectable()
export class FilterService {
public dataArr = [];
constructor(private httpService : HttpService) { }

setData() {
this.httpService.getData()
.subscribe((data) =>
{
const resultArr = [];
for(let key in data) {
resultArr.push(data[key]);
}
this.dataArr = resultArr; //console.log(resultArr) works in component.
}
)
}

getData() {
return this.dataArr;
}

}

component.ts

import { Component, OnInit } from '@angular/core';

import { FilterService } from '../../filter.service';

@Component({
selector: 'ubi-item-section',
templateUrl: './item-section.component.html',
styleUrls: ['./item-section.component.css']
})
export class ItemSectionComponent implements OnInit{
items = [];
filter;
constructor(private filterService : FilterService) { }

ngOnInit() {
this.filterService.setData();
this.items = this.filterService.getData()

}
}

最佳答案

您可以考虑在 this.dataArr 对象填满后立即从 setData 函数返回 promise。

代码

setData() {
return new Promise(resolve, reject) {
this.httpService.getData()
.subscribe((data) =>
{
const resultArr = [];
for(let key in data) {
resultArr.push(data[key]);
}
this.dataArr = resultArr;
resolve(this.dataArr); //resolve function will complete promise
}
);
}
}

您应该等待 setData 方法 ajax 完成,方法是将 then 调用放在 promise 上。

this.filterService.setData().then(
() => this.items = this.filterService.getData()
);

关于angular - 将数据从 service.ts 传输到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43034296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com