我正在构建一个angular nodejs app,两者之间的链接似乎不起作用(使用webservice)。
server.js
const express = require('express');
const app = express();
app.route('/recap').get((req, res) => {
res.send({
recap: [{ errors: 5 }]
});
});
app.listen(4200, () => {
console.log('Server started !');
});
recap.service.ts
getRecap(): Observable<Recap> {
return this.http.get<Recap>('api/recap')
.pipe(
tap(recap => this.log(`done`)),
catchError(this.handleError<Recap>('getRecap'))
);
}
回顾:
export class Recap{
errors: number;
}
RecapComponent(ts):
export class RecapComponent implements OnInit {
recap: Recap;
constructor(private recService: RecapService) { }
ngOnInit() {
this.getRecap();
console.log(this.getRecap()); // undefined
}
getRecap(){
this.recService.getRecap().subscribe(recap => this.recap = recap);
}
}
RecapComponent(html):
<ul>
<li>{{recap.errors}}</li>
<li>...</li>
</ul>
当我输入服务(http://localhost:4200/recap/)时,我将使用errors:
(空)的角度视图
当我输入节点server.js(http://localhost:4200/recap)时,我会{ errors: 5 }
(=这是我用nodejs发送的,但我没有角度视图)
看起来角度和节点之间的联系不起作用,我的错误在哪里?
编辑: 这是错误(使用ng服务): ERROR TypeError:无法读取属性&#39;错误&#39;未定义的 要清楚我在使用getRecap时的除外是错误= 5
答案 0 :(得分:0)
好的,我回到这里看到你还有问题,所以我想我会试一试。请注意,我知道很少的角度或rxjs所以这是不知情的,但它并不难运行:
1)你不能在4200上同时运行webserver和api,这很愚蠢。我知道angular有一些代理的东西,所以你可以指向/ api到另一个端口,但我不知道,也不想知道所以我想做的第一个想法是在4201上旋转api并将请求更改为:
return this.http.get<Recap>('http://localhost:4201/recap')
2)你必须意识到api-call会迟到。页面渲染后很久。但是你仍然有<li>{{recap.errors}}</li>
意味着模板会在调用之前寻找重新调整,并且在找不到它时会抛出错误。这些可能是您在控制台中看到的错误,以及您应该共享的错误。
轻松修复:设置默认值。您的构造函数中的this.recap = [];
。我还在组件类中添加了一个类成员声明,如下所示:@Input() recap: any;
。我不知道@Input实际上是什么,我不想知道,但我会假设它是绑定到模板的东西。哎呀,也许你甚至都不需要它。
3)你应该在你的传入XHR管道中做的第一件事,订阅 - 我以前从未使用过的)是记录你得到的东西:和{recap:[{errors:5}]这样的东西}。意味着它被包裹在某个东西中,所以我想这就是响应。所以我把这部分编辑成:
getRecap() {
this.recService.getRecap().subscribe((response: any) => {
// looooggg mee.
this.recap = response.recap;
});
}
到目前为止,你必须注意到你有一个数组而不是一个对象[ {errors:5} ]
所以我也更新了模板<li>{{recap[0].errors}}</li>
我确定你想在以后迭代它。< / p>
哦是的,组件构造函数constructor(private recService: RecapService) { };
这些只是传递给构造函数的参数,你需要保存服务,这样你就可以在构造函数之外使用它了
constructor(private recService: RecapService) {
this.recService = recService;
this.recap = [];
}
哦,还有一件事,因为我在另一个端口上提供API,我需要添加CORS的东西。如果你发现代理东西,我想你不需要它:
res.header('Access-Control-Allow-Origin', '*');
是的,我认为我所做的就是让它发挥作用。 css-background问题得到答案的原因是因为它们如此快速且易于重现。在任何公司中,某人必须投入的工作量才能找到您的控制台错误集合。人们免费这样做,所以不要嘲笑他们解决容易的问题。克隆的github回购很容易让那些愿意看这个的人减少20分钟的工作。
res.send({
recap: [{ errors: 5 }]
});