如何在休息webservice响应来之后渲染angular2 html页面

时间:2017-03-20 13:54:00

标签: rest angular typescript

我可以得到休息的webservice响应并在屏幕上安装它而没有任何问题。但不幸的是,在页面中我可以看到werbservice调用结果的初始值。在我收到wbservice的回复后,我需要做什么才能呈现页面?我的意思是我可以看到userInfo和userName的初始值。你可以看到下面的代码片段。

此致 阿尔珀

  export class NavigationComponent implements OnInit {
response:any;
errorMessage:any;
form:FormGroup;
obj = {"one": "", "two": "", "three": "", "four": ""};
webserviceUrl = "https://httpbin.org/post";
webServiceUrlGet = "https://jsonplaceholder.typicode.com/posts/1";
username = "alper"
userInfo = "alper Info";
componentName =  'AppComponent';

ngOnInit():void {
  this.getUserName();
}

 getUserName() {

this.http.get(this.webServiceUrlGet)
  .subscribe(
    function (data) {
      this.userInfo = data.json();
      this.username = this.userInfo.userId;


    },
    error => this.errorMessage = <any>error);
return this.username;
}

2 个答案:

答案 0 :(得分:7)

这不起作用

.subscribe(
  function (data)

应该是

.subscribe(
  (data) =>

this在回调中工作。

要仅在响应到达时呈现模板,您可以使用

<ng-container *ngIf="userInfo">
  <!-- actual template content here -->
</ng-container>

答案 1 :(得分:2)

我同意上面的建议使用胖箭。另一种方法是将'this'括在封闭中,如下所示:

export class NavigationComponent implements OnInit {
    response:any;
    errorMessage:any;
    form:FormGroup;
    obj = {"one": "", "two": "", "three": "", "four": ""};
    webserviceUrl = "https://httpbin.org/post";
    webServiceUrlGet = "https://jsonplaceholder.typicode.com/posts/1";
    username = "alper"
    userInfo = "alper Info";
    componentName =  'AppComponent';

    ngOnInit():void {
        this.getUserName();
    }

    getUserName() {
        let that = this;
        this.http.get(this.webServiceUrlGet)
        .subscribe(
            function (data) {
                that.userInfo = data.json();
                that.username = that.userInfo.userId;
            },
        error => that.errorMessage = <any>error);
        return that.username; // Return statement not necessary
    }
}