Angular HTTP GET未达到Express Route

时间:2018-12-26 14:49:34

标签: node.js angular

notification.service.ts中的我的Angular HTTP GET请求内部clearNotifications()没有命中Express Route route / notifications.js。我正在从名为app.component.ts的组件中调用clearNotifications()。我正在使用Angular 7 +

routes / notifications.js

const router = require('express').Router();

//Additional modules
// const db = require('../config/database');
// const notificationModel = require('../models/notifications');

//Test connection
// db.authenticate().then(() => {
//     console.log('Connection has been established successfully.');
// }).catch(err => {
//     console.error('Unable to connect to the database:', err);
// });

//Clear all notifications
router.get('/clear', (req, res, next) => {
    console.log('clear');
    // notificationModel.destroy({});
});

module.exports =路由器;

notification.service.ts

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class NotificationService {

  uri = 'http://localhost:5000'; 
  private socket = io(this.uri);

  constructor(private http: HttpClient) { }

  getNotification() {
    let observable = new Observable<{ string: String, number: String }>(observer => {
      this.socket.on('notification', (data) => {
        observer.next(data);
      });
      // return () => { this.socket.disconnect(); }
    })
    return observable;
  }

  clearNotifications() {
    return this.http.get(`${this.uri}/notifications/clear`);
  }
}

app.component.ts

import { Component } from '@angular/core';
import { NotificationService } from './notification.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [NotificationService]
})
export class AppComponent {
  title = 'client';

  string: String;
  number: String;
  notificationArray: Array<{ string: String, number: String }> = [];

  constructor(private notificationService: NotificationService) {
    this.notificationService.getNotification().subscribe(data => {
      this.notificationArray.push(data);
    });
  }

  clearNotifications() {
    this.notificationArray = [];
    this.notificationService.clearNotifications();
  }
}

2 个答案:

答案 0 :(得分:1)

您应该这样做:检查basic routing on express

var express = require('express');
var app = express();

app.get('/clear', (req, res) => {
    console.log('clear');

 res.send(success);
// notificationModel.destroy({});
});

还要确保从组件中subscribe进入服务方法。如果您不订阅,observables将不会执行。

您从哪里打来clearNotifications

订阅

组件中的clearNotifications,它将起作用:  this.notificationService.clearNotifications().subscribe( (data) => { ..})

  

作为发布者,您将创建一个Observable实例,该实例定义了订阅者函数。当使用者调用subscribe()方法时,将执行此函数。 订户功能定义了如何获取或生成要发布的值或消息

答案 1 :(得分:0)

angular中,http请求返回observable,因此您需要subscribe。如果observable没有任何订阅者,则不会执行该订阅者。试试

    clearNotifications() {
    return this.http.get(`${this.uri}/notifications/clear`)
               .subscribe(data => //your callback function,
                          error => // your error handler,
                          complete => // any after completion task);
  }