代码之家  ›  专栏  ›  技术社区  ›  Ashy Ashcsi

angular6 RxJs可观测问题

  •  1
  • Ashy Ashcsi  · 技术社区  · 7 年前

    我试图从组件中的服务类中检索TODO列表。但它不起作用。请在下面查找代码:

    待办事项。服务ts

    import { Injectable } from '@angular/core';
    import { Todos } from '../models/Todos';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Observable, of, BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class TodosService {
    
      todos: Todos[];
    
      httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
      }
    
      private todoSource = new BehaviorSubject<Todos>({ id: null, text: null, completed: null });
      selectedTodo = this.todoSource.asObservable();
    
      constructor(private http: HttpClient) {
        this.http.get<Todos[]>('http://localhost:8888/api/todos').subscribe((todos) => {
          this.todos = todos;
        });
      }
    
      getTodos(): Observable<Todos[]> {
        return of(this.todos);
      }
    
      addTodo(todo): Observable<Todos> {
        return this.http.post<Todos>('http://localhost:8888/api/todos', todo, this.httpOptions);
      }
    
      setTodo(todo: Todos) {
        this.todoSource.next(todo);
      }
    }
    

    Todolist。组成部分ts

    import { Component, OnInit } from '@angular/core';
    import { Todos } from '../../models/Todos';
    import { TodosService } from '../../services/todos.service';
    
    @Component({
      selector: 'app-todolist',
      templateUrl: './todolist.component.html',
      styleUrls: ['./todolist.component.css']
    })
    export class TodolistComponent implements OnInit {
    
      todos: Todos[];
      constructor(private _todosService: TodosService) {
      }
    
      ngOnInit() {
        this._todosService.getTodos().subscribe(todos => {
          console.log('getting todos', todos);
          this.todos = todos;
        });
      }
    
      onSelect(todo: Todos) {
        this._todosService.setTodo(todo);
      }
    }
    

    组件的ngOnInit方法调用服务的getTodos()方法。但在控制台日志中,TODO似乎没有定义。我做错了什么?

    谢谢

    2 回复  |  直到 7 年前
        1
  •  0
  •   Pankaj Parkar    7 年前

    理想情况下,ajax应该由 getTodos 方法本身。有人打电话进来 constructor 无法确保数据首先可用。异步就是这样工作的。它可以简单地返回如下。

    getTodos(): Observable<Todos[]> {
       return this.http.get<Todos[]>('http://localhost:8888/api/todos');
    }
    
        2
  •  0
  •   danday74    7 年前

    看起来您正在尝试缓存HTTP响应,以便在第二次调用getTodos()方法时不会发出第二个HTTP请求。

    如果我错了,那么@Pankaj Parkar是正确的。

    如果我是对的,那么你想这样做:

    getTodos(): Observable<Todos[]> {
      return (this.todos) ? of(this.todos) : 
        this.http.get<Todos[]>('http://localhost:8888/api/todos')
          .pipe( tap(todos => this.todos = todos) )
    }
    
    推荐文章