我正在尝试使用Angular从RESTApi获取数据。数据由使用HTTP get请求具有pvt属性departmentName的部门对象列表组成。
我正在尝试使用该列表更新角度材料下拉列表
我不断收到错误
Cannot read property "updateAvailableDepartment" of undefined
这是我的部门服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Department} from './department';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DepartmentServiceService {
private departmentURL: string;
constructor(private http: HttpClient) {
this.departmentURL = 'http://localhost:8080/department/departmentList';
}
public updateAvailableDepartment(): Observable<Department[]> {
return this.http.get<Department[]>(this.departmentURL);
}
}
这是部门课程
export class Department {
departmentName: string;
}
与下拉组件关联的组件类
import { Component, OnInit } from '@angular/core';
import {DepartmentServiceService} from '../department-service.service';
import {Department} from '../department';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
availableDepartments: Department[];
private departmentService: DepartmentServiceService;
constructor() {}
ngOnInit(): void {
console.log('hello');
this.departmentService.updateAvailableDepartment().subscribe(
data => { this.availableDepartments = data; },
error => { console.error('There was an error!', error); }
);
console.log('hello');
console.log(this.availableDepartments);
}
}
HTML代码的代码段
<mat-form-field>
<mat-label>Select a Department *</mat-label>
<mat-select>
<mat-option *ngFor="let department of this.availableDepartments"
[value]="department.departmentName">
{{department.departmentName}}
</mat-option>
</mat-select>
</mat-form-field>
任何建议或帮助将不胜感激。
答案 0 :(得分:0)
1-尝试在HTML中不使用 this ,例如
<mat-select>
<mat-option *ngFor="let department of availableDepartments"
[value]="department.departmentName">
{{department.departmentName}}
</mat-option>
</mat-select>
此是指为其渲染模板的组件本身。在模板上,您只能访问组件的成员。
2-在这样的构造函数中使用服务DepartmentServiceService
constructor(private departmentService: DepartmentServiceService) {}