【问题标题】:How To Subscribe To New Posts - Angular如何订阅新帖子 - Angular
【发布时间】:2020-09-08 11:39:50
【问题描述】:

我有这个 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>

问题是来自数据库的数据在没有页面刷新的情况下不会更新。 问题是我在 ngOnInit() 方法上从 DB 获取数据,该方法仅在 init 上调用。 如何修改 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;
    }
}

但我没有得到任何工作结果。

感谢您的宝贵时间!

【问题讨论】:

  • 您不能这样订阅您的数据库。您需要轮询或使用 SignalR 样式机制将更新推送到您的客户端。即使这样,如果您的数据库被其他应用程序修改,您也不会收到通知。
  • http 调用调用你的 api 从你的数据库中获取数据。它没有直接连接到它以获取更新。您要么需要依赖套接字通信,要么需要使用轮询来随着时间的推移进行额外的 http 调用
  • 您想“实时”查看数据库更改,而不刷新页面?使用 CRUD 操作,这是不可能的。有一次,我们必须做类似的事情,为此我们使用一个计时器作业(每 20 秒 httpget)。
  • @CirrusMinor 好主意,我要研究如何实现它。是的,这就是我想做的。感谢您的想法!
  • @GérômeGrignon 谢谢你的想法先生,我会搜索它!

标签: javascript node.js angular typescript


【解决方案1】:

您可以在某个时间间隔(例如一秒)安排加载位置。

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;
    });
}

【讨论】:

  • 这是正确的想法,但应该是this.mySubscription = interval(1000).pipe(map(() =&gt; this.http.get('http://localhost:8000/location')).subscribe(...)
猜你喜欢
  • 2013-01-06
  • 1970-01-01
  • 2016-07-05
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 2012-01-24
  • 2018-01-01
相关资源
最近更新 更多