0

Here is my code and if the console.log(data) in browser is

app.component.ts:34 [{"SemesterId":"Fall 2017"},{"SemesterId":"Spring 2017"}]

How can I convert this json string to an array and display it? this.result1=data['SemesterId']; doesn't work. Please take a look.

interface semester {
    SemesterId: string;

  }

@Component({
selector: 'app-root',
template: `
<ul>
  <li *ngFor="let h of result1">{{h}}</li>
  </ul>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';

constructor(private http: HttpClient) {

}

result1 :string;
r1:object;
ngOnInit(): void {
  this.http.get('http://localhost:13043/students/courses/all').subscribe(
    data=>{
      this.result1=data['SemesterId'];
      console.log(data);
    }      
  )
  }

}
1
  • Correct fix:result1 :object; Then, this.result1=(JSON.parse(data.toString())). Everything works! Commented Oct 2, 2017 at 17:12

2 Answers 2

1

change your service to

this.http.get('http://localhost:13043/students/courses/all').subscribe(
    data=>{
      this.result1=data;

    }      
  )

In your template

<ul>
  <li *ngFor="let h of result1">{{h.SemesterId}}</li>
  </ul>
Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't work.\n Cannot find a differ supporting object '[{"SemesterId":"Fall 2017"},{"SemesterId":"Spring 2017"}]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
change result1:string to result1:any[ ]
Type 'Object' is not assignable to type 'any[]'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
0

You have to map your response as follow:

this.http.get('http://localhost:13043/students/courses/all')
         .map((result) => result.json())
         .subscribe((data) => console.log(data));

Your endpoint is returning JSON string and you have to parse that into an object to use that in the way you want to.

You can also do it a different way, by calling:

this.result = JSON.parse(data);

9 Comments

It gives me an error. Property 'map' does not exist on type 'Observable<Object>'.
How do you import Observable typings? Can you post your import statements from that file?
import {Observable} from 'rxjs/Observable'; And my angular version is 4.4.4
Try to change that to import { Observable } from 'rxjs';
Yeah. I used rxjs, but it asked me to use Map. In addition, it said Value of type 'MapConstructor' is not callable. Did you mean to include 'new'?
|

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.