3

I can get rest webservice response and console it in screen without any problem. But unfortunately, in the page I can see initial value of the result of the werbservice call. What I need to do render the page after I get response from wbservice? I meant I can see userInfo and userName's initial values. You can see the snippet below.

Regards Alper

  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
  • I don't really understand what "render the page after I get response from wbservice" means. Please have a look at my answer. But I have doubts this is the whole story. Commented Mar 20, 2017 at 13:56
  • 1
    your answer is correct. I was using subscribe in a wrong way.Regards Commented Mar 20, 2017 at 14:02

2 Answers 2

7

This won't work

.subscribe(
  function (data)

It should be instead

.subscribe(
  (data) =>

for this to work inside the callback.

To only render the template when the response arrived you can for example use

<ng-container *ngIf="userInfo">
  <!-- actual template content here -->
</ng-container>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Günter.
2

I agree with the suggestion above to use fat arrows. An alternative may be to enclose 'this' in your closure as so:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.