как я могу получить доступ к переменным службы в шаблоне компонента в угловых - PullRequest
0 голосов
/ 17 июня 2019

У меня есть сервис, где я делаю запрос к API и получаю данные.затем в файле .ts я храню эти данные в служебной переменной.теперь проблема возникает, когда я пытаюсь получить доступ к этой служебной переменной в .html этого компонента xq, эта переменная не определена в .ts, то есть это не компонент, а служба.Как я могу получить доступ к этой служебной переменной из нескольких компонентов?

este es el codigo de mi servicio:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Inmueble } from '../modelos/inmueble';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class HostlistService {
  inmuebles: Inmueble[] = [];
  cabecera = {
    'Accept': 'application/json',
    'Authorization': ""
  }

  parametros = {
    'grant_type':'client_credentials',
    'client_id': 3,
    'client_secret': ''
  }


constructor(public http: HttpClient) {

}


obtenerToken(){
  return this.http.post<any>('https:',this.parametros);
}


obtenerInmuebles(resultToken){
  this.cabecera.Authorization=resultToken.token_type+" "+resultToken.access_token;
  console.log("----->"+this.cabecera.Authorization);
  return this.http.get<any>('',{ headers: new HttpHeaders(this.cabecera) });
}


}

Это код компонента, где вы вызвали эту службу и сохранили данные в переменной службы:

import { Component, OnInit, Input } from '@angular/core';
import { HostlistService } from '../servicios/hostlist.service';

import { Inmueble } from '../modelos/inmueble';
import { mergeMap } from 'rxjs/operators';


@Component({
  selector: 'app-slider',
  templateUrl: './slider.component.html',
  styleUrls: ['./slider.component.css']
})

export class SliderComponent implements OnInit {
  z: number=0;

  url: string = "URL";

  constructor(private hostlistService: HostlistService) { }
  ngOnInit() {
    this.hostlistService.obtenerToken()
      .pipe(
        mergeMap(resultToken => {
          //do whatever you want to do with the token
          //i.e. Save the token in the localstorage like this -
          localStorage.setItem("token",resultToken.access_token);
          return this.hostlistService.obtenerInmuebles(resultToken);
        })
      )
        .subscribe(
          result => {
            this.cargarJson(result);
          },error =>{
            console.log(error);
          }
        );
    }

    /*this.hostlistService.getInmuebles().subscribe(
      result => {
        console.log("-----------_>"+result.data);
      },error => {
        console.log(error);
      }
    );*/

  /*
  anteriorInmueble(){
    (this.i<=0) ? this.i=680: this.i=this.i-5;
    console.log("AntIn VALOR DE I: "+this.i);


  siguienteInmueble(){
    (this.i>=680) ? this.i=0: this.i=this.i+5;
    console.log("SigIn VALOR DE I: "+this.i);
  }*/


// metodo para cargar el Json recibido de la petición
  cargarJson(result){
    var foto1,foto2: string;
    foto1 = "fot0", foto2 = "fot";
    var precio: number=0;
    var i,j: number=1;

                for(const item of result.data) {
                    var pos: number=0;          //variable que define la posicion a almacenar en el vector
                    pos =0;
                    console.log("POS----->"+pos);
                    var inmueble = new Inmueble();
                    inmueble.fotos = [];
                    inmueble.nombre = item.nomb_prod_c;
                    inmueble.id = item.id_c;
                    inmueble.estacionamiento = item.estan_c;
                    inmueble.baño = item.banof_c;
                    precio = item.price;
                    precio = Math.round(precio*100)/100;
                    inmueble.precio = precio;
                      (item.fot01_c != "") ? (inmueble.fotos[pos]="fot01_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot02_c != "") ? (inmueble.fotos[pos]="fot02_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot03_c != "") ? (inmueble.fotos[pos]="fot03_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot04_c != "") ? (inmueble.fotos[pos]="fot04_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot05_c != "") ? (inmueble.fotos[pos]="fot05_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot01_c != "") ? (inmueble.fotos[pos]="fot06_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot02_c != "") ? (inmueble.fotos[pos]="fot07_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot03_c != "") ? (inmueble.fotos[pos]="fot08_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot04_c != "") ? (inmueble.fotos[pos]="fot09_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot05_c != "") ? (inmueble.fotos[pos]="fot10_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot01_c != "") ? (inmueble.fotos[pos]="fot11_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot02_c != "") ? (inmueble.fotos[pos]="fot12_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot03_c != "") ? (inmueble.fotos[pos]="fot13_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot04_c != "") ? (inmueble.fotos[pos]="fot14_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot05_c != "") ? (inmueble.fotos[pos]="fot15_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot01_c != "") ? (inmueble.fotos[pos]="fot16_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot02_c != "") ? (inmueble.fotos[pos]="fot17_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot03_c != "") ? (inmueble.fotos[pos]="fot18_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot04_c != "") ? (inmueble.fotos[pos]="fot19_c", pos++): (inmueble.fotos[pos]="");
                      (item.fot05_c != "") ? (inmueble.fotos[pos]="fot20_c", pos++): (inmueble.fotos[pos]="");
                      if(pos == 0){
                        inmueble.fotos[pos]="n";
                      }
                    this.hostlistService.inmuebles.push(inmueble);  //se almacena el inmueble en el vector de inmuebles


            }
            //console.log("************:"+this.inmuebles[1].fotos[0]);


    }

    anteriorInmueble(){
      (this.z<=0)? this.z=680: this.z=this.z-1;
    }


    siguienteInmueble(){
      (this.z>=680)? this.z=0: this.z=this.z+1;
    }



  consultarPais(){

  }
}

Я хочу иметь возможность доступа к массиву служб в многокомпонентном .html-шаблоне.Как я мог это сделать?Я читал это с наблюдаемыми и используя BehaviorSubject, но я ничего не понимаю в наблюдаемых больше, чем я прочитал, я не знаю, как это сделать.Заранее спасибо всем, кто может мне помочь, я был бы очень признателен.

1 Ответ

1 голос
/ 17 июня 2019

Сделайте ваш сервис общедоступным, как constructor(public hostlistService: HostlistService), тогда внутри шаблона вы можете сделать что-то вроде

<div *ngFor="let data of this.hostlistService.inmuebles">
  <span>{{data}}</span>
</div>

Короче говоря внутри шаблона используйте this.hostlistService.inmuebles для доступа к нему.

...