我想实现从剩余API获取列表的Angular示例。我尝试过:
SQL查询:
@Override
public Iterable<Merchants> findAll() {
String hql = "select e from " + Merchants.class.getName() + " e";
TypedQuery<Merchants> query = entityManager.createQuery(hql, Merchants.class);
List<Merchants> merchants = query.getResultList();
return merchants;
}
其他控制器:
@RestController
@RequestMapping("/merchants")
public class MerchantController {
@GetMapping("/list")
public Iterable<Merchants> getMerchantsList() {
return merchantRepository
.findAll();
}
}
服务:
@Injectable({
providedIn: 'root'
})
export class MerchantService {
constructor(private http: HttpClient) {
}
getList() {
return this.http.get("...../api/merchants/list");
}
}
组件:
@Component({
selector: 'app-terminal',
templateUrl: './terminal.component.html',
styleUrls: ['./terminal.component.scss']
})
export class TerminalComponent implements OnInit {
constructor(private terminalService: TerminalService,
private merchantService: MerchantService,
private router: Router,
private route: ActivatedRoute) {
}
merchants: Merchant[];
ngOnInit() {
this.merchantService.getList().pipe(
flatMap(params => {
return this.merchantService.getList();
})
).subscribe(value => {
if (value != null) {
this.merchants = value;
}
});
}
}
但是当我尝试使用该组件时出现错误:
ERROR in src/app/panel/terminal/terminal.component.ts(57,9): error TS2322: Type 'Object' is not assignable to type 'Merchant[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
src/app/panel/terminal/terminal.component.ts(57,9): error TS2322: Type 'Object' is not assignable to type 'Merchant[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Property 'includes' is missing in type 'Object'.
您能给我一些错的建议吗? 可能我的打字稿不正确吗?
答案 0 :(得分:2)
我有两个建议可以解决这个问题。首先,您可以指定getList
的返回类型:
getList(): Observable<Merchant[]> {
return this.http.get<Merchant[]>("...../api/merchants/list");
}
第二,我不确定这里是否正确使用了flatMap
运算符。除非您专门尝试针对每个响应再次调用该服务,否则您可以将其转换为:
this.merchantService.getList()
.subscribe(value => {
if (value != null) {
this.merchants = value;
}
});