如何在 Angular 中的页面加载时发出 HTTP 请求(使用按钮)

ske*_*on3 1 json http angular

当我的页面加载并在屏幕上显示响应文本时,我尝试向 API 发出 HTTP 请求。我正在使用 Angular 框架。

目前,当您按下按钮时,它会按照我的意愿工作。我想要按钮具有的确切功能,但它会在页面加载时自动发生。

//TypeScript
import { Component, OnInit } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';


@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})

export class ProfileComponent implements OnInit {



posts: Observable<String[]>;

  constructor(private http:HttpClient) {

  }

 public getPosts() {

  this.posts = this.http.get<any[]>('https://jsonplaceholder.typicode.com/posts');

  }


ngOnInit() {
  }

}
Run Code Online (Sandbox Code Playgroud)
//TypeScript
import { Component, OnInit } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';


@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})

export class ProfileComponent implements OnInit {



posts: Observable<String[]>;

  constructor(private http:HttpClient) {

  }

 public getPosts() {

  this.posts = this.http.get<any[]>('https://jsonplaceholder.typicode.com/posts');

  }


ngOnInit() {
  }

}
Run Code Online (Sandbox Code Playgroud)

这给了我一个带有按钮的页面。当我按下按钮时,我会从 API 获取信息。我希望 API 在页面加载时立即提供信息。

Cod*_*-EZ 5

只需调用 ngOnInit 上的方法

    ngOnInit() {
           this.getPosts()
      }
Run Code Online (Sandbox Code Playgroud)

或者你也可以像下面这样做

    export class ProfileComponent implements OnInit {
    posts: Observable<String[]> = this.http.get<any[]>('https://jsonplaceholder.typicode.com/posts');

      constructor(private http:HttpClient) {

      }
    }
Run Code Online (Sandbox Code Playgroud)