Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70448

Array with values returning undefined - Observable

$
0
0

@JGFAlmeida wrote:

I got 2 tables on the database, one named empresas and other named promocoes. Promocoes have the field idEmpresa where it recieves the value of the field idEmpresa, from empresas. When I print promocoes, I want to print as well one field of empresas. I’m trying to do this returning the result of ‘select * from empresas where idEmpresa=idEmpresa’, in php. I’m sure the service is working. But when I try to get idEmpresa from promocoes to make this works, it just don’t return any value. It says that the length of my array of promocoes is 0, but the same array is being printed with *ngFor on the html page. How can I solve it?
The Json my function that returns the value of ‘select * from promocoes’

[{"idPromocao":"1","idEmpresa":"3","promocao":"promo nova","dataInicio":"2019-04-04","dataFim":"2019-04-30","quantidade":"50","limite":"3","pontos":"1","descricao":"","foto":"","ativo":"1","idUsuario":"3"},{"idPromocao":"2","idEmpresa":"1","promocao":"promo nova","dataInicio":"2019-04-04","dataFim":"2019-04-30","quantidade":"100","limite":"5","pontos":"2","descricao":"","foto":"2019.04.04-13.06.10-01.jpg","ativo":"1","idUsuario":"3"},{"idPromocao":"3","idEmpresa":"3","promocao":"prom","dataInicio":"2019-04-04","dataFim":"2019-04-24","quantidade":"50","limite":"5","pontos":"5","descricao":"","foto":"","ativo":"1","idUsuario":"3"},{"idPromocao":"4","idEmpresa":"4","promocao":"teste","dataInicio":"2019-05-04","dataFim":"2019-05-11","quantidade":"12","limite":"1","pontos":"1","descricao":"

testeswdw<\/p>\r\n","foto":"","ativo":"1","idUsuario":"3"}]

The Json my function that returns the value of ‘select * from empresas where idEmpresa=idEmpresa’ idEmpresa=1

[{"idEmpresa":"1","empresa":"Pousada dos Reis","razaoSocial":"","documento":"","email":"teste@teste.com.br","cep":"","endereco":"","numero":"","complemento":"","bairro":"Portal da Ferradura","cidade":"Arma\u00e7\u00e3o de B\u00fazios","estado":"RJ","link":"www.teste.com.br","pontoCheckin":"10","pontoShare":"20","contato":"(99) 9999-9999 \/ (99) 9999-9999 \u2013 (99) 9999-9999","idCategoria":"4","idRoteiro":"4","descricao":"

Localizada em uma região privilegiada de Búzios e atuando no setor de turismo, a Pousada dos Reis oferece o charme de uma pousada com os serviços de hotelaria, com infraestrutura de lazer, espaço para eventos e restaurante.<\/p>\r\n","ativo":"1","dataCadastro":"2019-04-04 12:04:44","foto":"2019.05.07-12.15.47-01.jpg","idUsuario":"8"}]

Service functions
Promocoes

    findAll() : Observable<Promocoes[]>{
        return this.http.get<Promocoes[]>('http://localhost/sites/rioserramar/app/services/promocoes/promocoes.php');
    }

Empresas

findById(idEmpresa : number) : Observable<Empresa>{
        return this.http.get<Empresa>
        ('http://localhost.com.br/sites/rioserramar/app/services/empresas/empresas.php?idEmpresa='+idEmpresa);
    }

My Component ts

import { Component } from "@angular/core";
import { Promocoes } from "./promocoes";
import { PromocoesService } from "./promocoes-service";
import { UsuarioService } from "../usuario/usuario-service";
import { ToastController, NavController } from "ionic-angular";
import { RoteiroPage } from "../roteiro/roteiro.component";
import { EmpresaPage } from "../empresas/empresa.component";
import { ExplorePage } from "../explore/explore.component";
import { BlogPage } from "../blog/blog.component";
import { Roteiro } from "../roteiro/roteiro";
import { Empresa } from "../empresas/empresa";
import { EmpresaService } from "../empresas/empresa-service";

@Component({
    selector:'page-promo',
    templateUrl: 'promocoes.html'
})
export class PromocoesPage{
    promocoes : Promocoes[]=[];
    roteiro : Roteiro = new Roteiro();
    empresas : Empresa[]= [];
    pages : Array<{title : string, component : any, img : string}>


    constructor(private service : PromocoesService, private navCtrl : NavController, 
        private uservice : UsuarioService, private toastCtrl : ToastController, private emservice : EmpresaService){
        this.listar();
        console.log(this.empresas);
        this.pages = [
            {title:'Roteiros',component:RoteiroPage,img:'../assets/imgs/icones/icon-maps.png'},
            {title:'Empresas',component:EmpresaPage,img:'../assets/imgs/icones/icon-empresas.png'},
            {title:'Promocoes',component:PromocoesPage,img:'../assets/imgs/icones/icon-desconto.png'},
           {title:'Explorar',component:ExplorePage,img:'../assets/imgs/icones/icon-explorar.png'},
           {title:'Blog',component:BlogPage,img:'../assets/imgs/icones/icon-blog.png'},
          ];
    }

     async listar(){
        await this.service.findAll().subscribe((res)=>{
            this.promocoes = res;
        })
        await this.setEmpresas();
    } 
    setEmpresas(){
        
       console.log(this.promocoes.length);
       this.service.findAll().subscribe((data)=>{ 
           for(let i = 0; i < this.promocoes.length;i++){
        console.log(data[i].idEmpresa,' aaa');
    this.emservice.findById(data[i].idEmpresa).subscribe((res)=>{
        console.log(res);
        this.empresas[i] = res;
        console.log(this.empresas[i],'a')
    });
    }
       })
    }
    showToast(data : string){
      let toast = this.toastCtrl.create({
          message : data,
          duration : 3000,
          position : 'bottom'
      });
      toast.present();
  }
    cadCupom(idPromocao,custo){
        console.log(this.uservice.getLogado()[0].idUsuario,' ',idPromocao,' ',custo);
        if(this.uservice.getLogado()){
            this.service.saveCupom(this.uservice.getLogado()[0].idUsuario,idPromocao,custo).subscribe((res)=>{
                if(res !=null){
                    this.showToast('Cupom salvo');
                }else{
                    this.showToast('Cupom não salvo. Verifique seus pontos.');
                }
            })
        }else{
            this.showToast('É necessário estar logado para pegar o cupom');
        }
    }
    openPage(p){
      this.navCtrl.push(p.component,{
        roteiro : this.roteiro
      });
    
  }
}

my component html

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
      <ion-title>
        Rio Serra Mar
      </ion-title>
    </ion-navbar>
  </ion-header>
  
  <ion-content padding>
    <div class="bgAzul">
        <h3>faça o check-in e ganhe <br>
        <span>Compartilhe nas redes sociais e ganhe um bônus</span></h3>
      </div>
    <ion-list>
        <!-- <button (click)="mostrarBlog(blog)">
        <img src="../../assets/imgs/logo.png" width="300" height="300"/><br/>
        <h3>titulo</h3>
        <h4>data</h4>
    </button> -->
    <ion-item *ngFor="let item of promocoes; let i = index" [attr.data-index]="i"> 
         <div class="blogs" >
                  
               
                 
                    <strong><p style="font-size: 18px;text-transform: uppercase;">{{item.promocao}}</p></strong>
                    <span *ngIf="empresas.length >0 && empresas[i] != null">
                    <strong><p style="font-size: 14px;text-transform: uppercase;">{{empresas[i].empresa}}</p> </strong></span>
                    <span [innerHtml]="item.descricao"></span>
                  <p>PONTOS NECESSÁRIOS: <strong style="font-size:22px;">{{item.pontos}}</strong></p>
                    <button 
                    style="float:right;border-radius: 
                    10px;background-color: rgb(226, 170, 29);
                    color:white;padding:10px;" (click)="cadCupom(item.idPromocao,item.pontos)">PEGAR CUPOM</button>
                  
              
                  
                  
          </div>
        </ion-item>
      </ion-list>
      
</ion-content>
<ion-footer>
  <ion-navbar class="rodape">
    <ion-list *ngFor="let p of pages">
        <img src="{{p.img}}" alt="" tappable (click)="openPage(p)">
        <button (click)="openPage(p)">{{p.title}}</button>
    </ion-list>
  </ion-navbar>
</ion-footer> 


stuff being printed
Capturar

Thank you in advance. I hope I made myself clear.

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70448

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>