Average Joe Average Joe - 1 year ago 91
TypeScript Question

what would be the data type in this json like data?

I am creating an HTTP request to the back end thru this angular implementation.

I prepared the app.module by first importing the {HttpClientModule} from '@angular/common/http' into the app.module and then adding it to the imports array making it available to the rest of the app.

then, I use the get method on HttpClient to access the data in my server
That's the game plan.

The question is about determining the data type to be returned by the server.

The component has this code... I cut the not-needed stuff for brevity.

@Component(...)

export class MyComponent implements OnInit {

// results: string[]; // I am not sure about this

constructor(private http: HttpClient) {}

ngOnInit(): void {

url = 'http://example.com/authentication/get-username.php';

http
.get<MyJsonData>(url)
.subscribe...

}


My question is..
What should I type-cast where it says ? in the above code?

Little bit more backgrond:

the URL returns something like this:
{"wordpress_username":"admin_joe","user_role":"admin"}


or if no user logged in, this

{"wordpress_username":"","user_role":""}


now, here, we got a a format like {"x":"y", "j":"k"}
this is a json string. but, it is also an object

And this is where my confusion starts.

Would it be better to build an interface for this?
If so, what would be the interface look like?

Answer Source

Using Typescript is preferred for its strong typing also on the level of the Typescript. It is better to have a type for that.

In both cases you have the same shape of your object with two properties wordpress_username and user_role. Your interface can look like this

export interface MyJsonData {
   wordpress_username: string,
   user_role: string
}

Also if you can have a response with only one property, you can make them optional appending ? at the end of the property name

export interface MyJsonData {
   wordpress_username?: string,
   user_role?: string
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download