0

I want to parse a json response like that : { "code": "#546545" } from an angular 2 service. There are two ways that I know of:

  1. Use an interface

    export interface ProductId{ code: string; }

  2. Since json is a string use: angular.fromJson(code)

I think 1 is an overkill for a single string along with what I know what is the best way for something so simple?

8
  • observable and promise have .json() method, so whatever response you get, you can get your json by that method. Commented Aug 9, 2017 at 10:08
  • Also, can you please clarify if its angular or angularjs ? Commented Aug 9, 2017 at 10:10
  • Bhavik Patel AngularJs 2 could not find proper tag Commented Aug 9, 2017 at 10:12
  • 1
    there is no angularjs2 it is AngularJs , Angular, Angular4 Commented Aug 9, 2017 at 10:13
  • There is no such thing as AngularJS 2. its either Angular 2 or AngularJs. Are you using Typescript? Commented Aug 9, 2017 at 10:14

1 Answer 1

0

Either JSON.parse(string) or angular.fromJson(string)

which is just

function fromJson(json) {
  return isString(json)
      ? JSON.parse(json)
      : json;
}

The interface would help you, I don't think it's an overkill. But you still need to parse the string anyway.

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.