Angular订阅方法在最后执行

时间:2017-12-09 16:28:14

标签: angular typescript

我无法理解代码的执行顺序。在这里,我提供了收到的2个函数和输出:

component:

onSubmit(model) {
    this.submitted = true;
    let newUser: User;
    newUser = this.usersService.addUser(this.model);
    this.notifyParentOnAdd.emit(newUser);
    console.log('saved Model as json ' + JSON.stringify(newUser));

  }

service:

 addUser(user: User)  {
    let savedModel: User = new User('','','',['']);
    this.httpClient.post<User>('http://localhost:8080/user/create', user).
      subscribe(res => {
        console.log(res.id);
        console.log(res.firstName);
        console.log(res.lastName);
        console.log(res.groups);
        savedModel.id = res.id;
        savedModel.firstName = res.firstName;
        savedModel.lastName = res.lastName;
        savedModel.groups = res.groups;
      });
      console.log('user-service: ' + savedModel);
      console.log(JSON.stringify(savedModel));
      return savedModel;
  }

输出如下:

users.service.ts:35 user-service: [object Object]
users.service.ts:36 {"firstName":"","lastName":"","email":"","groups":[""]}
user-form.component.ts:33 saved Model as json {"firstName":"","lastName":"","email":"","groups":[""]}
users.service.ts:26 7
users.service.ts:27 test
users.service.ts:28 test
users.service.ts:29 ["WORKERS"]

它清楚地表明subscribe()方法在最后执行,这就是User对象为空的原因。

  1. 如何解释这种行为?

  2. 如何在调用服务方法subscribe()时强制addUser()执行?

0 个答案:

没有答案