Angular 6-可观察的订阅不起作用

时间:2018-09-19 09:17:54

标签: angular typescript angular6

我有以下情况。通常,服务是从服务器获取数据,并且该数据需要在其他组件中进行更新。

该组件仅获得一次订阅值,但是服务每2秒获取一次数据。我对其进行了测试,并且该服务做得很好。

对于我而言,不是在ngOnInit还是在构造器中

组件:

import {Component, OnInit} from '@angular/core';
import {TaskService} from "../../services/task.service";
import {Task} from "../../models/task";

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

  constructor(private taskService: TaskService) {
    this.taskService.getTasks().subscribe(tasks => {  // this is triggered only once, why ?
      this.tasks = tasks;
      console.log(tasks);
    });
  }

  ngOnInit() {

  }

  updateTask(task: Task) {
    try {
      task.completed = !task.completed;
      this.taskService.updateTask(task).subscribe();
    }
    catch (e) {
      task.completed = !task.completed;
    }
  }

}

服务

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable, of, timer} from "rxjs";
import {Task} from "../models/task";


const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};


@Injectable({
  providedIn: 'root'
})


export class TaskService {

  tasks: Task[];
  tasksURL = 'http://localhost:8080/api/tasks/';

  constructor(private http: HttpClient) {

    timer(1000, 2000).subscribe(() => {
      this.http.get<Task[]>(this.tasksURL).subscribe(value => this.tasks = value)
    }); // fetches and update the array every 2 seconds
  }

  getTasks(): Observable<Task[]> {
    return of(this.tasks); //returns observable which is than used by the component
  }

  updateTask(task: Task): Observable<Task> {
    const url = `${this.tasksURL}`;

    return this.http.post<Task>(url, task, httpOptions)

  }
}

2 个答案:

答案 0 :(得分:2)

在您的示例中,很明显,由于

,该服务每2秒获得一次
timer(1000, 2000).subscribe(() => {

在组件中,您的订阅完全没有间隔。由于getTask稍后不会发出事件,因此不会进行任何更新。

在组件中也使用计时器(不是很优雅)或手动发出.next

服务中:

public myObserver$: Subject<any>;
[...]
constructor(private http: HttpClient) {

  timer(1000, 2000).subscribe(() => {
    this.http.get<Task[]>(this.tasksURL).subscribe(value => {
      this.tasks = value;
      myObserver$.next(this.tasks);
    )}
  }); // fetches and update the array every 2 seconds
}

然后您可以在服务中订阅myObserver$而不是getTasks()方法。您不需要组件中的计时器。

您还应该将Subscription(订阅)存储在组件中的变量中:

private subscriptionRef: Subscription;

constructor(private taskService: TaskService) {
  this.subscription = this.taskService.getTasks().subscribe(tasks => {  // this is triggered only once, why ?
  this.tasks = tasks;
  });
}

,以便您可以取消订阅ngOnDestroy方法。

ngOnDestroy(): void {
  this.subscription.unsubscribe();
}

答案 1 :(得分:2)

您可以通过使用“主题/行为”来做您想做的事情:只需对服务进行一些更改

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export class TaskService {

  tasks: new BehaviorSubject<Task[]>([]);
  tasksURL = 'http://localhost:8080/api/tasks/';

  constructor(private http: HttpClient) {

     timer(1000, 2000).subscribe(() => {
       this.http.get<Task[]>(this.tasksURL).subscribe( (value) => { 
         this.tasks.next(value);
       })
     }); // fetches and update the array every 2 seconds
  }

  getTasks(): Observable<Task[]> {
        return tasks.asObservable(); //returns observable which is then used by the component
  }