You need to enable JavaScript to run this app. Angular 10下http.get的subscribe无法响应待办列表的POST/DELETE变更
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10下http.get的subscribe无法响应待办列表的POST/DELETE变更

待办列表应用数据更新问题

我使用Node.js搭建后端,Angular 2+技术栈搭建前端,开发一个简单的待办列表(todo-list)应用。已实现GET、POST、DELETE接口,所有接口运行状态正常。
存在的问题:当我订阅getTodos方法后,若待办列表通过POST或DELETE操作发生变更,我无法收到任何更新通知。

相关代码

todo.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Todo } from '../models/todo.model';

@Injectable()
export class TodoService {
  constructor(private http: HttpClient) { }

  getTodos(): Observable<Todo[]> {
    const baseUrl = 'http://localhost:3000/'
    const todoUrl = 'api/todo'
    return this.http.get<Todo[]>(baseUrl + todoUrl)
  } 
}

app.component.ts

const baseUrl = 'http://localhost:3000/'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [ TodoService ]
})
export class AppComponent implements OnInit {
  title = 'todo';
  taskHeader = ['User', 'Todo', 'Is done', 'Has attachment']
  todos: Todo[];

  constructor(private http: HttpClient, private todoService: TodoService) {}

  ngOnInit() {
    this.todoService.getTodos()
      .subscribe((res) =>  {this.todos = res
      console.log('this.todos', this.todos)}
    )
  }

  send(data) {
    const addUserUrl = 'api/todo'
    
    let addUserHeaders = new HttpHeaders().append('Content-Type', 'application/json');

    const todo: Todo = {
      userName: 'test',
      todo: data,
      isDone: true,
      hasAttachment: false
    }
    
    this.http.post(baseUrl + addUserUrl, todo,  {headers: addUserHeaders, responseType: 'text'}).subscribe((x) => console.log(x) )
  }  
  
  deleteTask(todoId) {
    const addUserUrl = 'api/todo'
    this.http.delete(`${baseUrl}${addUserUrl}/${todoId} `, {responseType: 'text'}).subscribe((s) => {
      console.log(s);
    })
  }
}

api.controller.js

module.exports = (app) => {
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: true }))

  app.get('/api/todo', (req, res) => {
    Todos.find({}).then(function (todos) {
      res.send(todos);
    });
  })

  app.post('/api/todo', (req, res) => {
    if (req.body.id) {
      Todos.findByIdAndUpdate(req.body.id, {
        todo: req.body.todo, isDone:
        req.body.isDone, hasAttachment:
        req.body.hasAttachment
      }, 
      (err, todo) => {
        if (err) throw err
        res.send('Post Success')
      })
    }

    else {
      const newTodo = Todos({
        userName: req.body.userName,
        todo: req.body.todo,
        isDone: req.body.isDone,
        hasAttachment: req.body.hasAttachment
      })
      newTodo.save((err) => {
        if (err) throw err
        res.send('Post Success')
      })
    }    
  });

  app.delete('/api/todo/:id', (req,res) => {
    Todos.findByIdAndRemove(req.params.id, (err) => {
      if (err) throw err
      res.send('Delete Success')
    })
  })
}

内容的提问来源于stack exchange,提问作者qwertyIsTheBest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 08:06:05