【问题标题】:Why can't I save my get request in angular?为什么我不能以角度保存我的获取请求?
【发布时间】:2020-11-05 00:15:34
【问题描述】:

您好,我从角度开始,我不知道为什么这没有任何帮助。

很简单,我发出一个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);
  }
}

这是我从浏览器看到的请求中得到的json

{"id":2,"username":"test","email":"test@test.com"}

但控制台显示的是

get: undefined

帮助!

【问题讨论】:

  • 这是控制台行console.log("get:" + this.userinfo);

标签: angular get httprequest


【解决方案1】:

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

其次,你的console.log 放错地方了。由于您放置它的位置,它会在 API 调用返回之前触发。

试试这个:

ngOnInit(): void {
   this.http.get<any>('/api/v0/user/userinfo?
    username=test').subscribe(data => {
      this.userinfo= data;
      console.log("get: " + this.userinfo);
   });
 }

原因是 API 调用需要时间来响应,并且代码继续执行下一条语句 console.log,这意味着 this.userdata 未设置为任何值,因为尚未从服务器返回任何数据.

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

【讨论】:

    【解决方案2】:

    这是我创建的堆栈闪电战上的一个链接,用于举例说明异步和同步:

    https://stackblitz.com/edit/angular-ivy-teoitv?file=src/app/hello.component.ts

    基本上史蒂夫为你描述了这个场景......

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

    另一个提示,你可以使用 rxjs “点击”到可观察对象内的 console.log。

    https://www.learnrxjs.io/learn-rxjs/operators/utility/do

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2021-01-07
      • 2021-03-14
      • 2011-04-22
      • 2019-01-18
      • 2013-10-17
      • 1970-01-01
      相关资源
      最近更新 更多