【问题标题】:Get user data with Angular httpClient使用 Angular httpClient 获取用户数据
【发布时间】:2020-09-17 23:33:52
【问题描述】:

我想获取用户数据,但总是得到 null。这是我的路线:

router.get('/user', (req,res)=>{ 
  res.send(req.user); 
})

不想详细说明,但是在 http://localhost:4000/auth/user 上,我有我的用户数据,当我登录时。

这是我的网络服务(所有服务的“框架”)获取部分:

constructor(private http:HttpClient) { }

  get(uri:string) {
    return this.http.get(`${this.devUri}/${uri}`)
  }

和AuthService(整体,因为它很短):

import { Injectable } from '@angular/core';
import { WebService } from './web.service';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private webService: WebService) { }

  getUser(){
    return this.webService.get('auth/user');
  }
}

以及具有此数据的组件:

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';

@Component({
  selector: 'app-public',
  templateUrl: './public.component.html',
  styleUrls: ['./public.component.css']
})
export class PublicComponent implements OnInit {

  user: any;
  constructor(private authService: AuthService) { }
  ngOnInit(): void {
    this.authService.getUser().subscribe( user => {
      this.user = user;
      console.log(user);
    })
  }

}

我确定地址或拼写错误没有问题,但我怀疑问题与异步有关,但我不知道如何解决。

【问题讨论】:

  • 其实异步代码是对的,这里少了点什么。查看您的开发工具的网络选项卡并验证来自服务器的响应是否包含数据。
  • 你确定你在服务器端启用了 cors 吗?您可以通过查看您的网络标签来检查它。
  • constructor(private http:HttpClient) { },把传过来的HttpClient赋值给this.http。

标签: javascript angular get request httpclient


【解决方案1】:

我认为这是服务器端代码问题,尝试如下更改。

router.get('/user', (req,res)=>{ 
 res.status(200).json({
   result: true,
   user: 'Test result'
  });
});

在你的组件中,onInit 方法添加如下

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';

@Component({
  selector: 'app-public',
  templateUrl: './public.component.html',
  styleUrls: ['./public.component.css']
})
export class PublicComponent implements OnInit {

  user: any;
  constructor(private authService: AuthService) { }
  ngOnInit(): void {
    this.authService.getUser().subscribe( result => {
      let temp:any = result;
      this.user = temp.user;
      console.log(this.user);
    })
  }

}

希望这应该可行。快乐编码!

【讨论】:

  • “对象”类型上不存在属性“用户”。我得到了唯一的结果:当我 console.log(result)
  • 是的,是的,您已将 req.user 放置在响应中,它不是 req.user,它可能是 req.body.user,您也可以尝试在用户响应中添加一个测试字符串,例如 hello world。
  • 现在未定义
  • 我找到了解决方案。我只需要启用凭据。请参阅上面的答案。
【解决方案2】:

找到解决方案:

在 server.js 中

app.use(
  cors({
    origin: "http://localhost:4200",
    credentials: true
  })
);

在 webService.ts 中:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  }),
  withCredentials: true 
}
get(uri:string) {
    return this.http.get(`${this.devUri}/${uri}`, httpOptions)
  }

它现在正在工作。

【讨论】:

    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多