Add an object to a arrey

Asked

Viewed 47 times

0

I’m trying to concatenate several objects so that they form a single arrey in my angular design. I’ll show you some code

selectFedd(user,feed){
      const key = user[0].userQueEuSigo
      feed.forEach(element => {
        if(element.keyUser == 2){
          this.publicacoes = [
              {
                keyUser:element.keyUser,
                id: element.id,
                user: element.user,
                photoUser:element.photoUser,
                photoPost: element.photoPost,
                curtidas: element.curtidas,
                comentarios: element.comentarios,
                pessoasQueCurtiu: element.pessoasQueCurtiu,
                totalComentarios:element.totalComentarios,
                like:element.like
              }
          ]
          console.log(this.publicacoes)
        }
      });
  }

this function takes as a meter stop a arrey with several objects and in that arrey I select only the ones that have the keyUser == 2, until then it is okay because if I run only this and give a console.log, me returns all 5 posts that have as keyUser the value 2. However this return are 5 objects and I’m having difficulties to add these 5 objects in my publication name variable.

I will leave my publications here.model.ts.

export interface Publicacao {
  keyUser: number,
  id: string,
  user:string,
  photoUser: string,
  photoPost: string,
  curtidas: number,
  comentarios: any[],
  pessoasQueCurtiu: any[],
  totalComentarios: number,
  like: boolean
}

in my Component.ts my variable is like ::: Publications: Publishing[] it’s like arrey because I’m iterating on it in my template with ngFor.

feed.componentts.

import { Component, OnInit } from '@angular/core';

import { Publicacao } from './publi/publi.model';
import { TestService } from '../test.service';
import { UserPrincipal } from './userPrincipal.model';


@Component({
  selector: 'app-feed',
  templateUrl: './feed.component.html',
  styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit {

  publicacoes: Publicacao[]
  feedFull: Publicacao[]
  userPrincipal: UserPrincipal[]

  constructor(private testeService: TestService) { }

  ngOnInit(){
//essa função pega todos os usuarios registrados no banco de dados Firebase
    this.testeService.read_userPrincipal().subscribe(data => { 
      this.userPrincipal = data.map(object => {
      return{
        token: object.payload.doc.id,
        bios: object.payload.doc.data()['bios'],
        id: object.payload.doc.data()['id'],
        imagePerfil: object.payload.doc.data()['imagePerfil'],
        nome: object.payload.doc.data()['nome'],
        seguidores: object.payload.doc.data()['seguidores'],
        seguindo: object.payload.doc.data()['seguindo'],
        totalPublicacoes: object.payload.doc.data()['totalPublicacoes'],
        user: object.payload.doc.data()['user'],
        userQueEuSigo: object.payload.doc.data()['userQueEuSigo'],
        publicacoes: object.payload.doc.data()['publicacoes']
      };})
        this.checkFollower(this.userPrincipal)
      });
  }
//essa checkFllower verifica se é um seguidor e retorna todas as publicações.
  checkFollower(primaryUser){
    const idPrimaryUser = 1//OK
    for(let i = 1; i < primaryUser.length; i++){ // for ta OK
      var arrey = primaryUser[i].userQueEuSigo
      if(arrey.indexOf(idPrimaryUser) == 0){
        this.testeService.carregar_publicacao().subscribe(data => {
          this.feedFull = data.map(publiObject => {
            return{
              keyUser: publiObject.payload.doc.data()['keyUser'],
              id: publiObject.payload.doc.data()['id'],
              user: publiObject.payload.doc.data()['user'],
              photoUser: publiObject.payload.doc.data()['photoUser'],
              photoPost: publiObject.payload.doc.data()['photoPost'],
              curtidas: publiObject.payload.doc.data()['curtidas'],
              comentarios: publiObject.payload.doc.data()['comentarios'],
              pessoasQueCurtiu: publiObject.payload.doc.data()['pessoasQueCurtiu'],
              totalComentarios: publiObject.payload.doc.data()['totalComentarios'],
              like: publiObject.payload.doc.data()['like']
            };})
              this.selectFedd(this.userPrincipal,this.feedFull)
           })
      }else{
        console.log('foi direto pro else')
      }
    }
  }

//essa é onde eu quero separar apenas as que tem a keyUser == 2
  selectFedd(user,feed){
      const key = user[0].userQueEuSigo
      feed.forEach(element => {
        if(element.keyUser == 2){
          this.publicacoes.push(element)
        }else{
          console.log('erro')
        }
      });
  }

}

Service archive

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';


@Injectable()

export class TestService {
  constructor(private firestore: AngularFirestore) { }
  /* create_NewIcecream : Cria um novo registro na coleção especificada usando o método add */
  criar_novo_user(record) {
    return this.firestore.collection('user').add(record);
  }
  /*read_Icecream: Chama o método snapshotChanges , que obterá registros e também será registrado para receber atualizações */
  read_userPrincipal(){
    return this.firestore.collection('user').snapshotChanges();
  }
  carregar_publicacao(){
    return this.firestore.collection('feed').snapshotChanges();
  }

}

1 answer

1

You have not quite understood the tools you are using, when you do the foreach() and the if() you already have the objects you need from the Api, you don’t need to create the object by passing the properties as you did, in which case it would just be push. I adapted an example just to demonstrate how it can be done with Vanilla to replicate there with Angular:

let publicacoes = [];                  // sua variável publicações 
let api = [                            // seria todos os objetos vindos da api
  {keyUser: 'ok', id: 1, user: 'Fulano'},
  {keyUser: 'no', id: 2, user: 'Ciclano'},   // esse não bate na condição do if
  {keyUser: 'ok', id: 3, user: 'Beltrano'}
];

api.forEach(elem => {
  if(elem.keyUser == 'ok') publicacoes.push(elem)  // insere no array os objetos
})

console.log(publicacoes)

In the class of the Angular component it would be basically:

public publicacoes: Publicacao;

selectFedd(user,feed){
  const key = user[0].userQueEuSigo
  feed.forEach(element => {
    if(element.keyUser == 2) this.publicacoes.push(element) 
  });
  console.log(this.publicacoes)
}
  • &#xA; selectFedd(user,feed){&#xA; const key = user[0].userQueEuSigo&#xA; feed.forEach(element => {&#xA; if(element.keyUser == 2){&#xA; this.publicacoes.push(element)&#xA; }else{&#xA; console.log('erro')&#xA; }&#xA; });&#xA; }&#xA; thus using is not working as it returns the following error ERROR Typeerror: Cannot read Property 'push' of Undefined excuse for delay

  • I edited the question by adding the full feed.compent.ts and test.service.ts

  • Strange John, for the error he commented is not finding the variable publications. There really do not know what would be!

  • saw the updated question , ta fuck this error kkkk

  • knows how to get direct publication by key in firebase?

  • Because I could take it right by the key you know

  • Putz do not know anything firebase, but, already tried to take the type of the variable and assign a normal array to see if it goes like this: publications = [ ]

  • Raccoon kkk worked man worked loaded all straight, thank you very much!!!! I’m redoing the instagram feed already solved me a fucking mistake, only that I’m not doing session management is just the same feed. Thank you so much

  • Nice that it worked João, success there!

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.