Angular ( service provider)

Clash Royale CLAN TAG#URR8PPPAngular ( service provider)
please i need your help .
i'm developping an hybrid app with ionic, angular, cordova and i created a service with the name piecesservice
import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
@Injectable()
export class PiecesService {
private donnes: any;
constructor(public http: HttpClient) {
}
getCote(nomCote, nomRobot) {
this.http.get('./assets/etat_pieces.json').subscribe(
data => {
this.donnes = data;
console.log(this.donnes);
for (var i = 0; i < this.donnes.cote.length; i++) {
if (this.donnes.cote[i].nom = nomCote) {
for (var j = 0; j < this.donnes.cote[i].robots.length; j++)
if (this.donnes.cote[i].robots[j].nom = nomRobot) {
console.log(this.donnes.cote[i].robots[j].pieces);
return this.donnes.cote[i].robots[j].pieces;
}
}
}
return this.donnes;
});
}
}
and a page pieces.ts
import { Component } from '@angular/core';
import {PiecesService} from "../services/pieces-service";
import { NavController, LoadingController } from 'ionic-angular';
import {Observable} from "rxjs";
//import {HttpClient} from "@angular/common/http";
@Component({
selector: 'page-pieces',
templateUrl: 'pieces.html'
})
export class PiecesPage {
info:any;
constructor(public nav: NavController, public piecesService: PiecesService) {
this.info = piecesService.getCote("Gauche", "Robot 2 DC 0912");
console.log(this.info);
}
}
.. the probleme is i can't read the data in the pieces.ts from the service it is mentionned undefined in the console.log(this.info);
please helpe me.
2 Answers
2
in pieces.ts
piecesService.getCote("Gauche", "Robot 2 DC 0912").subscribe(value => this.info = value);
subscribe
Your function getCote doesn't return anything. Normally you don't call subscribe until you are where you want to use your data and return the observable instead.
getCote
You could use the map function on the observable to transform the data before another part of your code subscribes to it.
map
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I don't think you can call
subscribetwice, can you?– Scotty Waggoner
3 mins ago