订阅方法中的Angular 2问题设置值

时间:2017-05-03 18:20:32

标签: javascript angular

我正在服务器上发帖子并尝试控制输出响应http代码。我使用chrome工具作为调试器来检查响应,我可以看到输出,但最后它转到订阅库做了一些事情并设置了函数而不是值。

  

我的组件类是

 export class MicroserviceCreateComponent implements OnInit{

   errorMessage: string;
   postMessage: string;
   teams: Team[];
   microservice: Microservice[];

    constructor(private microserviceService: MicroserviceService) { }

    ngOnInit() {
    }

  onSubmit({ value, valid }: { value: Microservice, valid: boolean }) {
     this.createMicroservice(value); 
     console.log(this.postMessage); <<<<<<<<==== This gives me undefined
  }

   createMicroservice(value){
      this.microserviceService.createMicroservice(value).subscribe(
        postMessage => this.postMessage = postMessage.valueOf(),
         error => {
          this.errorMessage = error.getMessage();
          console.error(error.getDescription());
        });
  }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

this.microserviceService.createMicroservice(value).subscribe( . . . )是一种非阻塞异步调用。这意味着在您调用它之后console.log(this.postMessage)可以在Web请求完成之前自由打印。尝试将console.log(this.postMessage)放入订阅中。

this.createMicroservice(value); // This is an async call
console.log(this.postMessage); // This happens immediately afterwards