页面初始化后加载 api 数据

Loading api data after page initialization

我在这个论坛上问我的第一个问题,因为我已经坚持了一段时间。 我应该指出,我不是 Angular 专家。

你知道如何加载页面,然后其中的一个组件吗?

例如,我有一个带有导航栏和 API 调用组件(显示 table)的页面。 我希望加载页面,我们看到导航栏,然后才激活 API 调用组件。

谢谢!

您可以使用 ngAfterViewInit 生命周期钩子来确保语句在视图完全初始化后执行。

您可以阅读更多相关内容here

基本上,您需要执行 ::

export SomeComponent implements AfterViewInit

ngAfterViewInit() {}

如果您将导航栏放置在单独的组件中并在单独的组件中填充 api 数据,请执行以下操作 ::

在您的导航组件中,

在 HTML 中:您可以放置​​ <router-outlet></router-outlet>

在 TS 中:在 ngAfterViewInit() 中,执​​行 router.navigate()

如果您觉得需要更多帮助,请添加评论:)

这是我为您整理的快速 StackBlitz,只需将请求部分相应地移动到所需的生命周期事件中即可。

我应该提一下,最好的做法是将实际请求移动到服务中,然后从组件中触发请求。

import {
  Component,
  OnInit,
  AfterViewInit
} from '@angular/core';
import {
  HttpClient
} from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
  todos: Array < Todo > ;

  constructor(private http: HttpClient) {
    this.http.get('https://jsonplaceholder.typicode.com/todos').subscribe((data: Todo[]) => {
      this.todos = data;
    });
  }

  ngOnInit(): void {
    console.log('ngOnInit');
  }

  ngAfterViewInit(): void {
    console.log('ngAfterViewInit');
  }


}
export interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

对于那些使用 router-outlet 和 url 标签的人,例如在 header 中,您可以使用 routerLink 只加载里面的组件(我最近发现了这个)。

例如,通过拥有“主”路径,您可以:

<a routerLink="/home">Home</a>

一些文档: 法语https://guide-angular.wishtack.io/angular/routing/mise-en-place-du-routing

英语: https://www.pluralsight.com/guides/activating-routes-with-routerllink-in-angular