检索到的mysql数据库对象中的字段都是未定义的

时间:2017-11-03 15:47:25

标签: java angular spring-boot spring-data-rest

我正在尝试使用角度4创建一个登录组件。在后端Spring启动时,使用Spring Data Rest和MySQL数据库。当我想使用检索到的帐户的登录凭据检查提交的登录详细信息时我无法这样做,因为检索到的帐户对象中的所有字段都是未定义的,而对象本身未定义(我使用if结构检查) )。有人可以看看我的代码,并告诉问题在哪里?我将从有角度的4类和服务开始,然后是帐户pojo和Spring REST存储库。

Angular 4班:

import {Person} from "./Person";
import {Role} from "./Role";
export class Account {
  id: number;
  username: string;
  password: string;
  person: Person;
  roles: Role[];

}

export class LaborPeriod{
    id: number
    beginDate: Date
    endDate: Date
    hours: number
}

import {LaborPeriod} from "./LaborPeriod";
export class Person{
    id:number
    name:string
    laborPeriods:LaborPeriod[]
}


export class Role{
    id: number
    name: string
}

登录组件类:

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AccountService]
})
export class LoginComponent {
  title: string;
  loginForm: FormGroup;

  constructor(private fb: FormBuilder,
              private accountService: AccountService,
              private router: Router) {
    this.title = "Inloggen";
    this.loginForm = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

  onSubmit() {
    const formModel = this.loginForm.value;

    const account: Account = this.accountService.authenticate(formModel.email, formModel.password);
    console.log(account.id + " " + account.password + " " + " " + account.username)
    console.log(account !== undefined)
    // if (account !== undefined) {
    //   this.router.navigate(["account/update", account.id]);
    // }
    // else{/*username or password doesent exist*/}
  }
}

帐户服务中的相关方法

  authenticate(username: string, password: string): Account {
    return this.restapi.postCredentials(username, password);
  }

RESTAPI:

@Injectable()
export class RestApiService {
  apiUrl: string = "/api/accounts";
  apiPostUrl: string = "api/accounts/search/findByUsernameAndPassword";
  data: Account;


  constructor(private http: Http) {}

  getData(){
    return this.http.get(this.apiUrl).map((res: Response) => res.json())
  }

  getContacts(){
    this.getData().subscribe(data=> {console.log(data); this.data = data})
  }

  postCredentials(username:string, password:string): Account {
    let params = new URLSearchParams();
    params.append("username", username);
    params.append("password", password);
    // params.set("username", "henk@gmail.com");
    // params.set("password", "12345");
    this.http.get(this.apiPostUrl, {params: params}).map((res: Response) => res.json()).subscribe(data=> { this.data = data});
    console.log(this.data);
    return this.data;
  }

}

现在用于后端的所有内容

@Entity
public class Account {
    @Id
    @GeneratedValue
    private Long id;
    private String username;
    private String password;
    @ManyToMany(cascade = CascadeType.ALL)
    private List<Role> roles;
    @OneToOne(cascade = CascadeType.ALL)
    private Person person;

@Entity
public class LaborPeriod {
    @Id
    @GeneratedValue
    private Long id;
    private Instant beginDate;
    private Instant endDate;
    private Integer hours;

@Entity
public class Role {
    //
    @Id
    @GeneratedValue
    private Long id;
    private String name;

@Entity
public class Person {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToMany(cascade = CascadeType.ALL)
    private Collection<LaborPeriod> laborPeriods;

帐户存储库

@RepositoryRestResource
public interface AccountRepository extends JpaRepository<Account, Long> {
    Account findByUsername(@Param("username") String username);
    Account findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}

非常感谢帮助。

2 个答案:

答案 0 :(得分:1)

您需要从帖子请求中返回一个Observable。这是异步,因此您的回复可在回调中找到。即使您尝试从回调subscribe尝试这样做,这也是不可能的,因为这是异步的。那么你需要从你的帖子请求中返回的是一个Observable:

return this.http.get(this.apiPostUrl, {params: params})
  .map((res: Response) => res.json())

在这里,您实际上可以从中间跳过authenticate方法,我不知道它对您有什么用处。但是如果你想保留它,当然你可以:)

那么你要做的就是在你的组件中订阅这个帖子请求。

constructor(private restApiService: RestApiService /** **/) { }

onSubmit() {
  const formModel = this.loginForm.value;
  this.restApiService.postCredentials(formModel.email, formModel.password);
    .subscribe(.....)
}

值得一读:How do I return the response from an Observable/http/async call in angular2?

答案 1 :(得分:0)

使用interface代替课程并将您的回复强制转换如下,

getData(){
    return this.http.get(this.apiUrl).map((res: Response) => <Account> res.json())
  }

注意:如果您正在使用类,则应该有一个构造函数来设置属性。