Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

600
Visualizações
Cómo actualizar un observable en angular2 después de un POST

Tengo una tabla que muestra información, al hacer clic en una fila de la tabla, el usuario puede actualizar los valores una vez que completa la solicitud, la tabla no se actualiza con los nuevos valores y debo hacer un F5 para actualizar la vista.

¿Cómo fuerzo una nueva solicitud de obtención al completar la solicitud?

aquí está el código relevante

MI SERVICIO

 import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import {Observable} from 'rxjs/Rx'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; // Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Device } from '../model/Device'; @Injectable() export class DeviceService { devices$: BehaviorSubject<Device[]>; constructor(private http : Http) { this.initializeDevices(); } initializeDevices() { var url = "./api/read/network/device"; //var url = '../assets/data/devices.json'; if (!this.devices$) { this.devices$ = <BehaviorSubject<Device[]>> new BehaviorSubject(new Array<Device>()); this.http.get(url) .map((res:Response) => res.json()) .subscribe(devices => { this.devices$.next(devices); }); } } subscribeToDevices(): Observable<Device[]> { return this.devices$.asObservable(); } }

mi componente

 import { Component, OnInit, ViewChild } from '@angular/core'; import { DeviceService } from '../../services/device.service'; import { MacService } from '../../services/mac.service'; import { Device } from '../../model/Device'; @Component({ selector: 'app-device-table', templateUrl: './device-table.component.html', styleUrls: ['./device-table.component.sass'] }) export class DeviceTableComponent implements OnInit { devices; //reference to the datatable needed to count filtered rows @ViewChild ('dt') dt; constructor(private deviceService : DeviceService, private macService : MacService) { } ngOnInit() { this.registerEvents(); this.getDevices(); } getDevices(){ this.deviceService.subscribeToDevices().subscribe( devices => this.processDevices(devices), error => console.log(error) ); } processDevices(devices){ //just data manipulation } emitShowDialogEvent(device) { if(!device.macAddress) { return; } this.macService.broadcastShowDialogEvent(device.macAddress); } registerEvents(){ this.macService.dataChangedEvent.subscribe(event =>{ console.log('data changed event'); this.getDevices(); //not provoking a new GET request to the API :( }); } }

Tengo otro componente, MACService, que al enviar una solicitud POST emite un evento que se captura como dataChangedEvent

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Dos formas que puedes usar.

Una es llamar a la solicitud GET dentro del evento de suscripción POST.

 this.guardianService.editGuardian(this.guardData).subscribe(res=> { this.loadData(); // this is function who makes GET request });

La otra forma es usar ReplaySubject.

 private subject: Subject<any> = new ReplaySubject<any>(1); get $getSubject(): Observable<any> { return this.subject.asObservable(); } loadData() { this._http.get(url, header) .map(x=>x.json()) .subscribe(data=> { this.subject.next(data); }); } postData(data) .....

Este es el Servicio. Aquí va componente

 this.serviceHandle.$getSubject.subscribe(res => { //here goes any thing you want to do. }); this.serviceHandle.loadData(); // this function will make reqeust this._accountService.editAccountData(account).subscribe(res=> { this.serviceHandle.loadData(); });
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda