【发布时间】:2019-03-22 16:19:47
【问题描述】:
我创建了一个我认为可以正常工作的后端 REST API。我认为它工作正常,因为当我在网络浏览器中导航到 http://localhost:43188/api/cat 时,我会看到一个打开/保存对话框,当我选择保存时,我会看到一个包含以下内容的 cat.json 文件:
[{"name":"Aap"},{"name":"Noot"},{"name":"Mies"}]
然后我创建了一个Angular6(前端)应用程序(ng new angular-project)并添加了一个猫组件(ng g c cat)并将文件cat.component.ts更改为:
import { Component, OnInit } from '@angular/core';
import { Observable, of } from "rxjs";
import { HttpClient } from "@angular/common/http";
import * as _ from 'lodash';
interface Cat {
name: string;
}
@Component({
selector: 'app-cat',
template: `
<ul *ngIf="cats$ | async as cats else noData">
<li *ngFor="let cat of cats">
{{cat.name}}
</li>
</ul>
<ng-template #noData>No Data Available</ng-template>
`})
export class CatComponent implements OnInit {
cats$: Observable<Cat[]>;
constructor(private http: HttpClient) {
}
ngOnInit() {
this.cats$ = this.http.get<Cat[]>('http://localhost:43188/api/cat');
}
}
并将我的 app.module.ts 更改为
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { CatComponent } from './cat/cat.component';
@NgModule({
declarations: [
AppComponent,
CatComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
但是当我现在添加时
<app-cat></app-cat>
在我的 app.component.html 中,当我运行 Angular 应用程序时,我得到“无可用数据”。
知道我做错了什么吗?
【问题讨论】:
-
我认为您需要在 ngIf 中的 else 之前添加一个分号,但如果这是真正的问题,我不这样做
-
您的模板看起来不错,尝试将localhost:43188/api/cat 加载到浏览器中,看看您会得到什么。或者使用点击操作符来控制台记录 http 调用的回复。
-
您能检查一下您的浏览器是否存在 CORS 问题吗?检查您的网络选项卡和控制台日志。如果 API 服务和 Angular App 不在同一个端口上运行,您的获取数据的请求将被浏览器阻止。
标签: angular angular6 angular-httpclient