我有关于get api的问题,这里是student_name在api的学生。下面是我尝试过的代码
接口{ "error": null, "result": [{"id": 1, "student_name": "Alex" }, {"id":2, "student_name": "Bob"}] }
打字:student.service.ts
listStudent(){
return this.http.get('api/student')
.map(HttpHandle.extractData.bind(null, 'list student'))
.catch(HttpHandle.handleError)
}http-handle.ts中的extractDate方法:
public static extractData(name: string, res: Response): Observable<Response> {
if (res.status < 300) {
console.log(`%c# Response status ${res.status}, ${name}, ${res.arrayBuffer().byteLength} bytes`,
'color: #00CC00; font-weight:bold;');
if (printDetail) {
console.groupCollapsed('\tResponse');
console.log(`${JSON.stringify(res, null, 2)}`);
console.groupEnd();
}
}
else {
console.log(`%c# Response status ${res.status}, ${name}, ${res.arrayBuffer().byteLength} bytes`,
'color: #CC0000; font-weight:bold;');
console.groupCollapsed('\tResponse');
console.log(`${JSON.stringify(res, null, 2)}`);
console.groupEnd();
}
return res.json();
}我的组件:student.component.ts
export class StudentComponent{
lstStudent: string[];// I think something went wrong
public student_name: string;
....
constructor(
private studentService: StudentService,
) { }
....
getStudents(){
this.studentService.listStudent()
.subscribe(data =>{
this.lstStudent = data['lstStudent'];
this.student_name = this.lstStudent...;//This is my issue
}
);
}Html
<select class="form-control" title="list Student"
[(ngModel)]="lstStudent" name="lstStudent">
<option *ngFor="let x of lstStudent" [ngValue]="x.student_name">{{x.student_name}}
</option>
</select>那么如何获取student_name并将其用于select标记中HTML。谢谢。
发布于 2017-08-03 20:14:25
在组件typescript文件中:
private selectedStudentId:number;
this.studentService.listStuden().subscribe(data => {
this.lstStudents = data['result'];
this.selectedStudentId = this.lstStudents[0].id;
});在您的html文件中:
<select class="form-control" [(ngModel)]="selectedStudent">
<option *ngFor="let student of lstStudents" value="{{student.id}}">
{{student.name}}</option>
</select>发布于 2017-08-03 19:24:10
您的代码中存在一些问题
1. in your student.component.ts declare lstStudent like below
lstStudent: any[];// change it to any[]
2. subscribe to the Observable like below in the getStudents() method
this.studentService.listStudent()
.subscribe(data =>{
this.lstStudent = data.result;
}
);
}
3. in your HTML, change the ngModel name to something like "StudentList" to avoid confusion with the lstStudent variable returned from service. You can get selected value from this ngModel name. I have used [value] property binding here.
<select class="form-control" title="list Student"
[(ngModel)]="StudentList" name="StudentList">
<option *ngFor="let x of lstStudent" [value]="x.student_name">{{x.student_name}}
</option>
</select>如果它起作用了,请告诉我。另外,您是否可以将extractData方法的代码发布到您的服务中,如下所示
.map(HttpHandle.extractData.bind(null, 'list student'))
https://stackoverflow.com/questions/45482085
复制相似问题