当我的Angular2组件发出请求获取我的假模型数据对象时,它会像这样返回:
_body: "[↵ {↵ "id": 0,↵ "title": "2017 Oscars",↵ "graphic": "https://wikitags.com/images/OscarsBanner.png",↵
我期待的是像这样的数组:
[
{ id: 0,
title: '2017 Oscars',
graphic: '/images/OscarsBanner.png',
categorycards: [ [Object], [Object], [Object], [Object] ] },
{ id: 1,
title: '2017 Super Bowl',
graphic: '/images/SuperBowlBanner.png',
categorycards: [ [Object], [Object], [Object], [Object] ] },
{ id: 2,
title: 'What people are talking about',
graphic: null,
categorycards: [ [Object], [Object], [Object], [Object] ] }
]
我的backend/models/home.ts
看起来像什么
export function homeData() {
return [
{
id: 0,
title: '2017 Oscars',
graphic: '/images/OscarsBanner.png',
categorycards: [
{
type: 'image',
graphic: 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Ryan_Gosling_2_Cannes_2011_%28cropped%29.jpg/1024px-Ryan_Gosling_2_Cannes_2011_%28cropped%29.jpg?width=440',
title: '2017 Oscar Nominee for Best Actor',
listings: ['Rayn Gosling', 'Denzel Washington', 'Andrew Garfield', 'Casey Affleck', 'Viggo Mortensen']
}
//...
]
}
//...
];
}
api.service.ts
@Injectable()
export class ApiService {
private getFeaturedUrl: string = '/wiki/api';
constructor(public http: Http) {}
/**
* Get featured categories data for homepage
*/
getFeatured(): Observable<{}> {
return this.http.get(`${this.getFeaturedUrl}/home`)
.do(res => console.log('getFeatured res', res))
.map(res => res.json().data)
.catch(this.handleError);
}
此处console.log
:
universalInit() {
console.log('universalInit...')
this.api.getFeatured()
.subscribe(categories => {
console.log('categories', categories);
// this.testFeaturedCategories = categories
});
// API CRUD ////////////////////////////////////////////////////////////////////
app.get('/wiki/api/home', (req, res) => {
console.log('homeData()', homeData());
if (!homeData()) returnError(res, 'No home data found');
res.json(homeData());
});
在终端中,我看到我的home.ts
模型数组:
为什么我的res.body看起来很高兴?
答案 0 :(得分:2)
看起来它可能正在尝试将json对象转换两次。虽然不完全确定
而不是res.json(homeData())
尝试:
res.send(homedata())
如果这不起作用,那么我的猜测就是转向角度并改变
.map(JSON.parse(res.json().data))