I'm new to angular and ionic and i have to develop an application that can connect to a backend and get users data. The application is able to extract user data, but not to save them in a variable with subscribe method.
The 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;
}
}
Home:
<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);
}
}
The return JSON is like this:
{"people": [{"gender":"female","name":{"title":"miss","first":"willemien","last":"heslinga"},"email":"[email protected]"},{"gender" : "male", "name":{"title":"monsieur","first":"bernard","last":"olivier"},"email":"[email protected]"}]}
My app can read the json file, but can't save it. Runs the console.log but fails to put active in this.people
Subject<T>. You would instead expose an observable (asObservable()) based on the subject from the service and subscribe that to that instead. Also, why even use a subject in your example, why not just consume the data ofgetPeople()directly?