简体   繁体   English

如何使用 Angular Observable

[英]How to use Angular Observable

I have got problem with getting user information using http request to my rest api server, I don't know what is wrong....我在使用 http 请求获取用户信息到我的 rest api 服务器时遇到问题,我不知道出了什么问题....

When user click on login button, Angular send request to server with username and password, if is correct it returns user info else it returns null.当用户单击登录按钮时,Angular 将使用用户名和密码向服务器发送请求,如果正确则返回用户信息,否则返回 null。 Problem is that variable user in user service is still null though the username and password are correct.问题是尽管用户名和密码正确,但用户服务中的变量 user 仍然为空。

I don't know how to solve this problem, so if you help me I will be happy !我不知道如何解决这个问题,所以如果你帮助我,我会很高兴! Thank for any help.感谢您的帮助。

REST API: REST API:

package cz.flay.fellcms.http;

import cz.flay.fellcms.dao.UsersRepository;
import cz.flay.fellcms.entities.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping(path = "/api/users")
public class UsersRestController {

    @Autowired
    private UsersRepository usersRepository;
    Logger logger = LoggerFactory.getLogger(UsersRestController.class);

    @CrossOrigin
    @GetMapping(path = "/all")
    public @ResponseBody Iterable<User> getAll(){
        return usersRepository.findAll();
    }

    @CrossOrigin
    @GetMapping(path = "/verify", params = {"username", "password"})
    public @ResponseBody User verify(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password){
        logger.info("t");
        return usersRepository.verify(username, password);
    }
}

User Service用户服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../entities/User';

@Injectable()
export class UserService {

  private usersUrl: 'http://localhost:8080/api/users';

  user: User;
  verifyUrl: string;

  constructor(private http: HttpClient) {}

  isLoggedIn() {
    return this.user != null;
  }

  isAdmin() {
    return this.user.isAdmin;
  }

  unLoggin() {
    this.user = null;
  }

  login(username: string, password: string) {
    this.verifyUrl = 'http://localhost:8080/api/users/verify?username=' + username + '&password=' + password;
    this.http.get<User>(this.verifyUrl).subscribe(data => this.user = data);
    if (this.user != null) {
      return true;
    } else {
      return false;
    }
  }

}

You're calling if (this.user !== null) too soon.if (this.user !== null)调用if (this.user !== null) That evaluation will get called before the request goes away and back.该评估将在请求消失和返回之前被调用。 Try this:试试这个:

login(username: string, password: string) {
    this.verifyUrl = `http://localhost:8080/api/users/verify?username=${username}&password=${password}`;
    return this.http.get<User>(this.verifyUrl)
        .map(data => {
            this.user = data
            if (this.user != null) {
               return true;
            } else {
                return false;
            }
        });
}

The thing is though, wherever you call this login method, it's now an observable you have to subscribe to, not a sync method.问题是,无论您在何处调用此login方法,它现在都是您必须订阅的 observable,而不是同步方法。

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

相关问题 如何处理 Observable<response></response> - How to process Observable<Response> 如何在Angular5和spring-boot中使用自定义验证器 - How to use custom Validator in Angular5 and spring-boot 如何在春季靴子Thymeleaf中使用角度双向绑定标签 - How to use angular two way binding tag in spring boot Thymeleaf 如何在angular js中使用http.post检索已检查的数据表中的行? - How to I use http.post in angular js to retrieve the rows of my datatable that are checked? 如何使用 Apache 作为 Angular/Spring-Boot 的代理来防止 CORS 场景? - How to use Apache as proxy for Angular/Spring-Boot to prevent CORS-scenario? 如何在我的 angular 应用程序中调用和使用 spring REST POST API 返回没有正文的字符串? - How to call and use the spring REST POST API in my angular app which is returning string without body? 使用<a>标签在 HTML 和 Angular 中打开一个弹出窗口</a> - Use <a> tag to open a popup window in HTML and Angular Spring + Angular:如何以角度解析 ResponseEntity? - Spring + Angular: How to parse ResponseEntity in angular? 如何使用spring boot和angular 2登录 - how to login with spring boot and angular 2 如何通过POST注销Angular / Spring - How to Logout in Angular / Spring by POST
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM