簡體   English   中英

來自C#Rest Service的Angular 4 json對象

[英]Angular 4 json object from c# rest service

我有一個簡單的服務,它將json字符串發送到json組件中。 如何訪問組件中json的各個元素。 響應如下。

GetExamResult:
"{"Question":"This is the Question","Answer1":"This is 
Answer1","Answer2":"This is Answer2","Answer3":"This is 
Answer3","Answer4":"This is Answer4","Correct":1}"

我已經嘗試過this.answer1 = data [0] .answer1;

但是它將變量定義為undefined。

這樣嘗試

getData(){
    this.httpClient.get('someservice')
    .subscribe(
      (data:any[]) => {
        this.ques1 = data[0].GetExamResult.Question1;
        console.log(this.ques1);

  }
)

數據是一個對象,您可以直接訪問為

 this.answer1 = data.answer1;

您可以使用JSON.parse

var json = '{"result":true, "count":42}';
obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42

console.log(obj.result);
// expected output: true

以您的情況為例:

var getExamResult = '{ "Question": "This is the Question", "Answer1": "This is Answer1", "Answer2": "This is Answer2" }';
var obj = JSON.parse(getExamResult);

console.log(obj.Answer1);
// expected output: This is Answer1
console.log(obj.Answer2);
// expected output: This is Answer1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM