【问题标题】:Angular 6 : Real time dataAngular 6:实时数据
【发布时间】:2020-10-11 22:07:03
【问题描述】:

我有一个应用程序,用户可以在其中添加评论,并显示评论,我的问题是直到我刷新页面才显示 cmets。

我希望在用户单击输入或提交按钮后显示评论

这是我目前所拥有的:

  1. 获取数据service.ts

    this.activeRouter.params.subscribe((params) => {
      let id = params['id'];
      this.moviesService.getComments(id)
        .then(comments => {
          console.log(comments);
          this.comments = comments;
        });
    });
    

2.然后显示到前端:html

   <div *ngFor="let comment of comments" class="col-md-7">
          <ul class="list-group">
            <li class="list-group-item">Author: {{comment.author}}</li>
            <li class="list-group-item">Comments: {{comment.description}}</li>
          </ul>
          <br>
        </div>

不幸的是,当我的服务器更新 JSON 时,html 根本不会更新,直到我刷新页面然后我才能看到添加的 cmets 错误

我在代码中缺少什么来完成我想要的?虽然是新手

【问题讨论】:

    标签: javascript angular html


    【解决方案1】:

    您的代码很好,但不幸的是,Promise 只能解析为一个值。

    但是,可观察对象可以为您提供实时数据流!

    使 moviesService.getComments() 方法返回一个可观察的对象,该可观察对象返回 cmets。

    它应该看起来有点像这样(假设您使用 angular HttpClient 来获取 cmets):

    // movieService.service.ts
    
    import { HttpClient } from '@angular/common/http'
    
    ...
    
    constructor(
      private http: HttpClient
    )
    
    getComments() {
      return this.http.get<Comments>(url)
    }
    
    ...

    你可以像这样使用 observable:

    // comment.component.ts
    
    ...
    
    comments: Observable<Comments>
    
    ...
    
    ngOnInit() {
      this.comments = this.movieService.getComments()
    }
    
    ...

    最后在模板中:

    // comments.component.html
    
     <div *ngFor="let comment of comments | async" class="col-md-7">
      <ul class="list-group">
        <li class="list-group-item">Author: {{comment.author}}</li>
        <li class="list-group-item">Comments: {{comment.description}}</li>
      </ul>
      <br>
    </div>

    【讨论】:

    • Hii @mateja 那么在哪种情况下我们应该考虑使用promise?
    • observable 最酷的地方在于它们用途广泛。您可以使用它们来处理数据流或单个值,无论是同步的还是异步的。这就是为什么我总是倾向于使用 observables 和 rxjs。但是如果你
    • 唉,但是如果你只想得到一个值而不是流,那么使用 Promise 就好了。关于这个主题有很多很棒的资源,比如stackoverflow.com/questions/37364973/promise-vs-observable 和并排比较youtube.com/watch?v=jgWnccjXR4I
    【解决方案2】:

    使用异步管道和 Observables Angular 中的管道就像 Linux 中的管道一样工作。它们接受输入并产生输出。输出将由管道的功能决定。这个管道接受一个 promise 或 observable 作为输入,它可以在 promise 被解析或 observable 发出一些新值时更新模板。与所有管道一样,我们需要在模板中应用管道。

    假设我们有一个 API 返回的产品列表,并且我们有以下可用服务:

    // api.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class ApiService {
    
      constructor(private http: HttpClient) { }
    
      getProducts() {
        return this.http.get('http://localhost:3000/api/products');
      }
    
    }
    

    上面的代码很简单——我们指定了返回 HTTP GET 调用的 getProducts() 方法。

    是时候在组件中使用这个服务了。我们在这里要做的是创建一个 Observable 并将 getProducts() 方法的结果分配给它。此外,我们将每 1 秒调用一次,因此如果 API 级别有更新,我们可以刷新模板:

    // some.component.ts

    import { Component, OnInit, OnDestroy, Input } from '@angular/core';
    import { ApiService } from './../api.service';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/interval';
    import 'rxjs/add/operator/startWith';
    import 'rxjs/add/operator/switchMap';
    
    @Component({
      selector: 'app-products',
      templateUrl: './products.component.html',
      styleUrls: ['./products.component.css']
    })
    
    export class ProductsComponent implements OnInit {
      @Input() products$: Observable<any>;
      constructor(private api: ApiService) { }
    
      ngOnInit() {
        this.products$ = Observable
          .interval(1000)
          .startWith(0).switchMap(() => this.api.getProducts());
      }
    
    }
    

    最后但同样重要的是,我们需要在模板中应用异步管道:

    <ul>
      <li *ngFor="let product of products$ | async">{{ product.prod_name }} for {{ product.price | currency:'£'}}</li>
    </ul>
    

    这样,如果我们将新项目推送到 API(或删除一个或多个项目),更新将在 1 秒内显示在组件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 2020-01-22
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多