我是角度和离子技术的新手,我必须开发一个可以连接到后端并获取用户数据的应用程序。 该应用程序能够提取用户数据,但不能将其保存在变量中 使用订阅方法。
PeopleService:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ReplaySubject } from 'rxjs';
import {map} from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class PeopleService {
public activeProject:ReplaySubject<any> = new ReplaySubject(1);
public people: any;
constructor(public http: HttpClient ){
console.log("Ciaooo");
}
getPeople() {
this.http.get('.....................').pipe(map(res => res)).subscribe(res => this.activeProject.next(res));
return this.activeProject;
}
}
首页:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
import { Component, OnInit } from '@angular/core';
import {PeopleService} from '../../people-service.service';
import { ReplaySubject } from 'rxjs';
console.log("ouu");
@Component({
selector: 'app-start-p',
templateUrl: './start-p.page.html',
styleUrls: ['./start-p.page.scss'],
providers: [PeopleService]
})
export class StartPPage implements OnInit {
//public people : any;
public people : any;
constructor(public peopleService : PeopleService){
console.log("Start p page costruito richiamo loadPeople");
}
ngOnInit() {
this.people = null;
console.log("loadPeople avviato, provo a inviare richiesta pacchetti a peopleService.getPeople");
this.peopleService.getPeople();
this.peopleService.activeProject.subscribe(active => {this.people = active, console.log(active)});
console.log(this.people);
}
}
返回的JSON是这样的:
{"people": [{"gender":"female","name":{"title":"miss","first":"willemien","last":"heslinga"},"email":"willemien.heslinga@example.com"},{"gender" : "male", "name":{"title":"monsieur","first":"bernard","last":"olivier"},"email":"bernard.olivier@example.com"}]}
我的应用程序可以读取json文件,但无法保存。运行console.log,但无法使它活跃于this.people
答案 0 :(得分:1)
我会尝试对该设置进行一些重组,以使其保持简单并使其正常运行。如评论中所述,我们可以直接使用getPeople()
。如下所示。请确保从RxJS导入Observable
。
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
private getPeople():Observable<any> {
return this.http.get(//filler details//).pipe(map(data => data)
);
}
请注意,上面的函数设置为返回“可观察”,这意味着您可以像这样直接在组件中进行订阅。
this.peopleService.getPeople().subscribe(data => {
console.log(data); // is good, should show you people.
}, error => {
console.log(error); // HttpError will provide error and type.
});
这消除了涉及subject
的复杂逻辑,同时为您提供了所需的功能。任何问题都会发表评论。 BR。