M
M
METAH2018-03-30 12:02:58
JSON
METAH, 2018-03-30 12:02:58

How to properly get an array of strings from WebAPI?

Hello.
I'm new to web development, so please don't kick too hard :)
So, there is a certain component. here is the constructor code in typescript:
export class TestC {
public CBVals: string[];
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
http.request(baseUrl + 'api/Data/GetCBVals').subscribe(response => { this.CBVals = response.json()}) ;
console.info("CBVALS= " + this.CBVals);
}
}
Here's the .NET Core 2.0 server-side code:
[HttpGet("[action]")]
public List GetCBVals()
{
List vals = new List();
vals.Add("one");
vals.Add("two");
vals.Add("three");
return vals;
}
Judging by the console, this.CBVals=undifined variable. However, in the same console you can see the server's response - ["one","two","three"]
Question - why is this variable undefined?
And the question after - how to pass an array of strings back to WebAPI?
I've already broken my head

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Yudakov, 2018-03-30
@METAH

1. You have console output:
console.info("CBVALS= " + this.CBVals);
fires before a response is received.
It makes sense to put this code after the response is received:
this.CBVals = response.json();
console.info("CBVALS= " + this.CBVals);
2. Second point, what kind of "this" comes from "subscribe"? - It may not be an instance of "TestC" at all.
For reliability inside the constructor, I propose to declare the first line:
var that = this;
and in the rest of the constructor code, change all "this" to "that".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question