0

Hi I have a simple controller that returns a simple (I’ve simplified it all for this post):

  [HttpGet("[action]")]
  public AppSettings GetStuff()
  {
        var stuff = new Stuff { Dummy = ”Hi”; };
        return stuff;
  }

  public class Stuff
  {
    public string Dummy { get; set; }
  }

All good, now I call it from my Angular service:

getStuff(): Observable<IStuff> {
    return (this.httpClient
        .get<IStuff>(this.localUrl)
        .pipe(
            catchError(this.errorHandlerSerevice.handleError)
        )) as any;
} 

Here’s my IStuff:

export interface IStuff {
    Dummy?: string;
}

All good… The console shows me 200 and the response…

But when I subscribe to getStuff() from my component I get [object object] or udentified… I have tried a god few subscriptions but no luck:

stuff: IStuff;

getStuff(){
    this.stuffService.getStuff()
        .subscribe(stuff => this.stuff = stuff); 
}
Or:
getStuff(){
    this.stuffService.getStuff()
        .subscribe((data: IStuff) => this.stuff = {
            Dummy: data['Dummy']
        });
}

Any idea?

4
  • 2
    Where exactly are you getting [object object] or udentified? On the console? Where exactly did you log the response? Commented Nov 8, 2018 at 15:52
  • The console returns the json object as expected. I get the undefined during the subscription binding: stuff => this.stuff = stuff, Or when stepping through the code and hovering over data['Dummy']. Commented Nov 8, 2018 at 15:56
  • If I do this for instance .subscribe(data => { this.stuff = data; alert(data); }); I get [Object Object].... Commented Nov 8, 2018 at 16:00
  • That's because alert will call toString() on your object, which will result in [Object object]. If you want the JSON format, you'll need to call JSON.stringify yourself Commented Nov 8, 2018 at 16:00

1 Answer 1

3

When you do this:

instance .subscribe(data => { this.stuff = data; alert(data); });

You're trying to print data on an alert box. But since data is a JavaScript Object, you're seeing [Object object] as the alert will call toString on it. If you want the actual contents to be printed, you'll have to stringify it.

Try this:

alert(JSON.stringify(data));

This should print the actual response.

Sign up to request clarification or add additional context in comments.

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.