【问题标题】:How to call a method in HTML other than (click)="method()"如何在 HTML 中调用除 (click)="method()" 之外的方法
【发布时间】:2019-03-25 19:27:16
【问题描述】:

向 wordpress api 调用 GET 请求。当页面加载到使用 angular 的离子应用程序中时,我将如何显示数据。

我可以获得我想要的帖子列表,但只有当我在按钮上使用(单击)来调用 HTML 中的方法时。我已经完成了关于 Udemy 的课程,这是我第一次尝试使用 Angular 构建离子应用程序,所以我什至可能不需要该方法?

HTML

<ion-content>

  <button (click)="onGetPosts()">Get Posts</button>
  <ion-list>

    <ion-item *ngFor="let post of posts">
      <ion-title>
        {{ post.title.rendered }}
      </ion-title>
    </ion-item>
  </ion-list>

</ion-content>

for-sale.page.ts

export class ForSalePage implements OnInit {

  posts: any;

  constructor(private saleService: ForSaleService) { }


  ngOnInit() {

  }

  onGetPosts() {
    this.saleService.getPosts()
      .subscribe(
        (posts: any) => this.posts = posts,
      );

  }
}

for-sale.service.ts

export class ForSaleService {

  posts: any;


  constructor(private http: HttpClient) { }

  getPosts() {
    return this.posts = this.http.get('http://***/wp-json/wp/v2/posts');

  }

}

因此,当单击按钮时,它会按预期检索帖子列表,然后在 *NgFor 中对所需数据进行字符串插值。但是我只能通过单击按钮首先加载数据。

id 之类的,是在页面打开后立即加载所有数据。

我怀疑我可能不需要方法?由于这是唯一需要此数据的页面,但我想不出任何其他方法。

谢谢

【问题讨论】:

    标签: html angular typescript ionic-framework


    【解决方案1】:

    调用ngOnInit()中的方法

    ngOnInit() {
       this.onGetPosts()
    }
    

    【讨论】:

    • 哦,哇当然。非常感谢。我实际上尝试过使用 OnInit,但我把整个 onGetPosts() 代码都放在了,从来没有想过这样做。
    【解决方案2】:

    看看Angular Lifecycle Hooks:

    有了这个钩子,你可以在组件的不同生命周期内执行代码。

    在你的情况下 OnInit 应该工作。

      import { OnInit } from '@angular/core';
    
      export class ForSalePage implements OnInit {
    
      posts: any;
    
      constructor(private saleService: ForSaleService) { }
    
    
      ngOnInit() {
        this.saleService.getPosts()
          .subscribe(
            (posts: any) => this.posts = posts,
          );
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2021-06-11
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多