简体   繁体   中英

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....

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. Problem is that variable user in user service is still null though the username and password are correct.

I don't know how to solve this problem, so if you help me I will be happy ! Thank for any help.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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