首页 > 解决方案 > 如何以角度在所有打开的选项卡中呈现更新的数据

问题描述

我正在使用 Angualr、Node、express 和 socketio 构建一个演示应用程序。我有一个带有服务器端分页的表和一个用于在表中添加记录的按钮(模型)。这个想法是当我创建新记录时,它应该更新 mongodb 集合并发出一个事件并在所有打开的选项卡中重新加载新数据。此应用程序在一个选项卡(视图)中运行良好,但如果我看到其他选项卡,则该组件具有新数据,但不会反映在视图中。看起来即使组件中的变量具有新值,然后角度也不会在所有选项卡中呈现视图。有人可以帮我吗?

组件.ts

import { Component, OnInit } from '@angular/core';
import { StockService } from './stock.service'
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import {io} from 'socket.io-client';

const socket= io('http://localhost:5000',{transports: ['websocket', 'polling', 'flashsocket']})

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

  POSTS: any;
  page = 1;
  total=1
  itemPerPage=5
  loading: boolean | undefined;
  
  public record={
    Open:0,
    Close:0
  }
  
  constructor(private stockService: StockService,private modalService: NgbModal) {
  
   }
   

  closeResult: string='';
  open(content:any) {
    this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }
  
  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return  `with: ${reason}`;
    }
  }
saveData(modal:any){
  this.stockService.createPost(this.record) .subscribe(
    response => {
    },
    error => {
      console.log(error);
    });
  modal.close('Data saved')
  
}

  ngOnInit(): void {
    socket.on('stockUpdated',async()=>{
      this.fetchPosts(this.page,this.itemPerPage);
    })
    this.fetchPosts(this.page,this.itemPerPage);
  }

  fetchPosts(page:number,limit:number): void {
    this.loading = true;
    this.stockService.getAllPosts(page,limit)
      .subscribe(
        response => {
          this.POSTS = response.docs;
          this.total=response.totalDocs
          this.loading = false;
          console.log('POSTS: ',this.POSTS)
          console.log('total: ',this.total)
          
        },
        error => {
          console.log(error);
        });
  }

  getPage(event:any){
    this.page = event;
    this.fetchPosts(this.page,this.itemPerPage);
  }
}

服务.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';


const endpoint = 'http://localhost:5000/api/stock';

@Injectable({
  providedIn: 'root'
})

export class StockService {

  constructor(private http: HttpClient) { }

  getAllPosts(page:number=1,limit:number=10): Observable<any> {
    console.log('params: ',page)
    return this.http.get(`${endpoint}?page=${page}&limit=${limit}`);
  }
  createPost(params:any=1): Observable<any> {
    return this.http.post(endpoint, params );
  }

}

html



<div class="container">
    <h3 class="text-center mt-5 mb-5">
      Stock table
    </h3>
    

    <table class="table">
      <thead>
        <tr>
          <th>Date</th>
          <th>Open</th>
          <th>Close</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let post of POSTS | paginate : { id: 'server', itemsPerPage: itemPerPage, currentPage: page, totalItems: total };
          let i = index" >
          <th scope="row">{{post.Date}}</th>
          <td>{{post.Open}}</td>
          <td>{{post.Close}}</td>
        </tr>
      </tbody>
    </table>
  
    <div class="d-flex justify-content-center">
      <div class="spinner" [ngClass]="{ 'hidden': !loading }"></div>
    <pagination-controls (pageChange)="getPage($event)" id="server"></pagination-controls>
    </div>
    <br>
    <button class="btn btn-lg btn-outline-primary" (click)="open(mymodal)">Add New</button>
  </div>

   
<ng-template #mymodal let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">Add new record</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    <form>
        <div class="form-group">
          <label for="recipient-name" class="col-form-label">Open:</label>
          <input name='open' [(ngModel)]="record.Open"  type="text" class="form-control" id="recipient-name">
        </div>
         <div class="form-group">
          <label for="recipient-name" class="col-form-label">Close:</label>
          <input name='close' [(ngModel)]="record.Close"  type="text" class="form-control" id="recipient-name">
        </div>
      </form>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('Cancel click')">Cancel</button>
    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="saveData(modal)">Save</button>
  </div>
  
</ng-template>

标签: javascriptnode.jsangularsocket.io

解决方案


推荐阅读