简体   繁体   English

使用 Angular httpClient 获取用户数据

[英]Get user data with Angular httpClient

I want to fetch user data, but I always get null.我想获取用户数据,但总是为空。 Here's my route:这是我的路线:

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

Don't want to go into the details, but on http://localhost:4000/auth/user, I have my user data, when I am logged in.不想深入细节,但在 http://localhost:4000/auth/user 上,我有我的用户数据,当我登录时。

Here's my web service("framework" to all services) get part :这是我的网络服务(所有服务的“框架”)获取部分:

constructor(private http:HttpClient) { }

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

and AuthService(whole, because it's short):和 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');
  }
}

And component with this data:以及具有此数据的组件:

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);
    })
  }

}

I am sure, that there is no problem with addresses or typos, but I suspect, that the problem is connected with asynchronism, but I don't know how to fix it.我确信地址或拼写错误没有问题,但我怀疑问题与异步有关,但我不知道如何解决。

I think it's server side code issue try changing that as followed.我认为这是服务器端代码问题,请尝试按以下方式更改。

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

And in you component while onInit method add as followed在你的组件中, 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);
    })
  }

}

Hopefully this should work.希望这应该有效。 Happy Coding!快乐编码!

Found the solution:找到了解决办法:

In server.js在 server.js 中

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

In webService.ts:在 webService.ts 中:

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

and it's working now.它现在正在工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM