【发布时间】:2018-09-20 14:17:05
【问题描述】:
我有以下情况。服务通常是从服务器获取数据,这些数据需要在其他组件中更新。
组件仅获取一次订阅值,但服务每 2 秒获取一次数据。我测试了它,服务做得对。
如果 subscirption 在 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)
}
}
【问题讨论】:
-
你需要在你的服务中使用BehaviorSubject medium.com/@weswhite/…
标签: angular typescript angular6