我有这个post-list.component.ts:
import { Component, Input, OnInit, OnDestroy } from '@angular/core';
import { Location } from '../post.model';
import { PostsService } from '../posts.service';
import { Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css'],
})
export class PostListComponent implements OnInit, OnDestroy {
model: Location[] = [];
constructor(private http: HttpClient, public postsService: PostsService) {}
ngOnInit() {
// this.postsService.getPosts().subscribe((res) => {
// this.model = res;
// });
this.http.get<any>('http://localhost:8000/location').subscribe((res) => {
this.model = res.location;
});
//this.showPosts();
}
showPosts() {
this.postsService.getPosts().subscribe((res) => {
this.model = res.location;
});
console.log(
this.postsService.getPosts().subscribe((res) => {
this.model = res;
})
);
}
onShow(_token: string) {
var find = this.model.find(({ token }) => token === _token);
this.postsService.setLat(find.lat);
this.postsService.setLng(find.lng);
console.log(
this.postsService.getLat() + ' ' + this.postsService.getLng()
);
}
ngOnDestroy() {}
}
这个post-list.component.html
<mat-accordion multi="true" *ngIf="model.length > 0">
<mat-expansion-panel *ngFor="let post of model">
<mat-expansion-panel-header>
{{ post.token }}
</mat-expansion-panel-header>
<p>{{ post.lat }}</p>
<p>{{ post.lng }}</p>
<mat-action-row>
<button mat-raised-button color="accent" (click)="onShow(post.token)">
GET COORDS
</button>
</mat-action-row>
</mat-expansion-panel>
</mat-accordion>
<p class="info-text mat-body-1" *ngIf="model.length <= 0">No posts added yet</p>
问题是来自数据库的数据在没有页面刷新的情况下不会更新。 问题是我只能通过init从ngOnInit()方法上从数据库获取数据。 如何修改ngOnInit()方法以订阅来自数据库的数据?
我尝试处理的posts.service.ts是:
import { Location } from './post.model';
import { Injectable } from '@angular/core';
import { Subject, Observable, Subscription, from } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class PostsService {
constructor(private http: HttpClient) {}
model: Location[] = [];
private lat;
private lng;
getPosts() {
return this.http.get<any>('http://localhost:8000/location');
}
setLat(lat) {
this.lat = lat;
}
setLng(lng) {
this.lng = lng;
}
getLat() {
return this.lat;
}
getLng() {
return this.lng;
}
}
但是我没有任何工作结果。
感谢您的时间!
答案 0 :(得分:0)
您可以安排在一定时间间隔(例如一秒钟)内的装载位置。
mySubscription: Subscription;
ngOnInit() {
this.mySubscription = interval(1000).subscribe(() => {
this.loadLocation();
});
}
loadLocation() {
this.http.get<any>('http://localhost:8000/location').subscribe((res) => {
this.model = res.location;
});
}