如何将事件从nodeJS / express发送到angular

时间:2018-07-23 05:42:38

标签: node.js angular express

我的交易记录很长,我想通知客户进度。我的前端是Angular 4,后端是nodeJS / Express。客户端通过HTTP Post发起事务。 Angular确实提供了侦听事件进度的功能。 https://angular.io/guide/http#listening-to-progress-events

我的问题是,如何将事件从我的Express应用程序发送到Angular应用程序? 到目前为止,我不想使用sockets.io。

2 个答案:

答案 0 :(得分:0)

听上传进度事件实际上是一项客户端功能。它在后台执行的操作是根据客户端(即浏览器)已发送到服务器的数据量来告诉您进度。实际上,它并没有从服务器收到服务器已收到多少数据然后向用户显示进度的响应(就像我想的那样)。因此,如果您从逻辑上和技术上进行思考,那么它就无济于事。而且,据我所知,套接字是实时更新服务器端发生的事情的唯一方法。

答案 1 :(得分:0)

根据Angular的文档,进度事件可以由客户端处理,经过一些搜索,我发现了服务器端事件-SSE,它基本上是发送带有活动连接头的响应头,然后是进度数据。 我能够做到,但是仍然存在每个角度发送和处理自定义用户事件的问题。这就是我所拥有的。

App component.ts

import { Component ,OnInit} from '@angular/core';
import { CommonService} from './common.service';
import { Observable,Subscription } from "rxjs/Rx";
import 'rxjs/add/operator/timeout';
@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css','../../node_modules/bootstrap/dist/css/bootstrap- 
 theme.min.css']
})

export class AppComponent implements OnInit {
 private sseStream: Subscription;
 messages:Array<string> = [];
 progress:number=0;
 totalProgress:number=7;
 constructor(private commonService: CommonService ) { }

 ngOnInit(){
  this.commonService.getHttpObj().subscribe(event=>{
  if(event){
   if(event['loaded']){
   console.log(event['loaded']);
   this.progress=(event['loaded'] / this.totalProgress)*100;
  }
 }
});
}
title = 'Angular4';
}

common.service.ts

import { Injectable } from '@angular/core';
import {HttpRequest} from '@angular/common/http';
import { Observable } from "rxjs/Rx";
import { catchError, map, tap , last} from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { HttpEventType } from '@angular/common/http';
const req = new HttpRequest('GET', 'http://localhost:9080/event', {
 reportProgress: true
});

@Injectable()
export class CommonService {

constructor(private http: HttpClient) { }

getHttpObj(){
 return this.http.request(req).pipe(
   map(event => this.getEventMessage(event)),
   tap(message => this.showProgress(message)),
 //   last(), // return last (completed) message to caller
 //  catchError(this.handleError())
 );

};

private getEventMessage(event: any) {
switch (event.type) {
  // case HttpEventType.Sent:
  //   return `Uploading file `;

  case HttpEventType.UploadProgress:
    // Compute and show the % done:
    const percentDone = Math.round(100 * event.loaded / event.total);
    return `File  is ${percentDone}% uploaded.`;

  case HttpEventType.Response:
    return `Complete`;
  case HttpEventType.User:
    return event;
  case HttpEventType.UploadProgress:
    return `${JSON.stringify(event)}`;
  case HttpEventType.DownloadProgress:
    return event;        
  default:
    return event;
 }
}

showProgress(a:any){
  //console.log(a);
  return a;
 }



 private handleError<T> () {
  return (error: any): Observable<T> => {

  // TODO: send the error to remote logging infrastructure
 //    console.error('error'); // log to console instead

   // TODO: better job of transforming error for user consumption
 //    console.log(`${error.message}`);

  // Let the app keep running by returning an empty result.
    return null;
  };
  }
 }

app.component.html

`<div class="container">
  <div style="text-align:center">
  <h1>
  Welcome to {{title}}!!
 </h1>
 <input type="text" [(ngModel)]="test">
 <p>{{test}}</p>
 </div>
 <div class="progress"> 
   <div class="progress-bar bg-success" [ngStyle]="{'width':progress + '%'}"></div>
 </div>
 </div>  `

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
import { ServerComponent } from './server/server.component';
import { ServersComponent } from './servers/servers.component';
import { HttpClientModule } from '@angular/common/http';
import {CommonService } from './common.service';
import { HttpModule } from '@angular/http';
@NgModule({
 declarations: [
 AppComponent,
 ServerComponent,
 ServersComponent
  ],
 imports: [
  BrowserModule,
  FormsModule,
  HttpClientModule,
  HttpModule
  ],
  providers: [CommonService],
  bootstrap: [AppComponent]
 })
export class AppModule { }

server.js

var express=require('express');
var app=express();
app.listen(9080);

app.get('/event',(req,res)=>{

res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });


        setTimeout(() => {
        res.write( "\n") ;
        setTimeout(() => {
            res.write("\n") ;
            setTimeout(() => {

                res.write( "\n") ;
                setTimeout(() => {
                    res.write( "\n") ;
                    setTimeout(() => {
                        res.write( "\n") ;
                        res.write(JSON.stringify({})) ;
                        res.end();
                        },
                        2000);
                    },
                    2000);
                },
                2000);
            },
            2000);
        },
        2000);


 [enter image description here][1]});