Angular 为什么可以';我不能保存我的get请求吗?

Angular 为什么可以';我不能保存我的get请求吗?,angular,get,httprequest,Angular,Get,Httprequest,你好,我是从angular开始的,我不知道为什么这没有任何帮助 这很简单,我发出一个get请求,我试图保存数据,但我做不到,我向您展示了代码 import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-profile', templateUrl: './

你好,我是从angular开始的,我不知道为什么这没有任何帮助

这很简单,我发出一个get请求,我试图保存数据,但我做不到,我向您展示了代码

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ProfileComponent implements OnInit {
  userinfo;
  constructor(private readonly http: HttpClient) {
  }
  ngOnInit(): void {
    this.http.get<any>('/api/v0/user/userinfo?username=test').subscribe(data => {
      this.userinfo= data;
    });
    console.log("get: " + this.getuser);
  }
}
但它通过控制台显示的是

get: undefined

救命啊

首先,正如Luis在评论中提到的,您需要在
console.log
语句中访问正确的变量

其次,您的
控制台.log
位于错误的位置。它是在API调用返回之前触发的,因为您将它放在了何处

试试这个:

ngOnInit(): void {
   this.http.get<any>('/api/v0/user/userinfo?
    username=test').subscribe(data => {
      this.userinfo= data;
      console.log("get: " + this.userinfo);
   });
 }
ngOnInit():void{
this.http.get('/api/v0/user/userinfo?
用户名=测试“)。订阅(数据=>{
this.userinfo=数据;
log(“get:+this.userinfo”);
});
}
原因是API调用需要时间来响应,代码继续执行下一条语句console.log,这意味着this.userdata没有设置为任何值,因为还没有从服务器返回任何数据


在进一步讨论之前,您需要了解异步与同步函数。这是web应用程序中的一个重要概念。

这里是我创建的stackblitz上的一个链接,用于举例说明异步和同步:

基本上Steve为你描述了这个场景

基本上,来自端点的响应中的“延迟”会返回这个未定义的值,但这可以在从服务器接收响应时通过加载来处理,这里有一个想法

另一个技巧是,您可以使用rxjs“tap”在一个可观察对象中console.log


这是控制台行console.log(“get:+this.userinfo”);
ngOnInit(): void {
   this.http.get<any>('/api/v0/user/userinfo?
    username=test').subscribe(data => {
      this.userinfo= data;
      console.log("get: " + this.userinfo);
   });
 }