pass component data to a service in angular 6

1

Hello friends, I have a doubt, it is possible to send data to service from one component and then from the service to send them to another component. in this code I have errors but in case what I would like is to pass the data array that is in the first component to the service and after the service sent it to component 2, and beforehand thanks for the help

component 1

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import {DatoscompraService} from './../datoscompra.service'



@Component({
  selector: 'app-carteras',
  templateUrl: './carteras.component.html',
  styleUrls: ['./carteras.component.css']
})
export class CarterasComponent implements OnInit {
  datos:any = [
    {
      producto:'Cartera 1',
      cantidad: 3,
      precio:200
    },
    {
      producto:'Cartera 2',
      cantidad: 1,
      precio:500
    },
  ];

  constructor(private servicio:DatoscompraService) { }

  ngOnInit() {
  }

  public enviar(){
    return this.datos;
  }

}

service

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DatoscompraService {

 datoss:any[] = [];

  constructor() { }

  public enviarPara(){

  }




}

component 2

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import {DatoscompraService} from './../datoscompra.service'




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

  datos:any[] = [];

  constructor(private servicio:DatoscompraService){
    this.datos = servicio.enviarPara();
  }

  ngOnInit() {
  }

}
    
asked by jhon sanchez 21.10.2018 в 21:58
source

1 answer

1

If the components are not parent and child, the way to pass data between them is through services. I leave you a possible solution. In the service you have to have a set and a get . The set is to 'save' what you send from component 1 in the service and the get to send them to any other component, in this case to component 2

setArray(array: any) {
  this.arrayDelService = array;
}

getArray() {
  return this.arrayDelService;
}

In component 1 create a method that receives that array and then call it from ngOnInit

sendArray(datos) {
  this._service.setArray(datos);
}

In component 2 create a variable that will paint what the service sends you. This you do from ngOnInit

ngOnInit() {
  this.arrayDesdeService = this._service.getArray();
}

And finally, in the html of component 2 you paint the array with a *ngFor

<ul *ngFor="let item of arrayDesdeService">
  <li>{{item.producto}}</li>
  <li>{{item.cantidad}}</li>
  <li>{{item.precio}}</li>
</ul>

Since it's a bit of a mess, you can see it working here

Greetings

    
answered by 22.10.2018 / 09:39
source