当我的页面加载并在屏幕上显示响应文本时,我尝试向 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, …Run Code Online (Sandbox Code Playgroud)