我遇到了api问题,这里是api学生student_name
。这是我试过的代码
阿比
{
"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。
谢谢。
答案 0 :(得分:2)
在您的组件打字稿文件中:
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>
答案 1 :(得分:1)
您的代码中存在一些问题
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'))