Javascript 从nodejs获取json数据到Angular 6
我的Javascript 从nodejs获取json数据到Angular 6,javascript,node.js,angular,typescript,Javascript,Node.js,Angular,Typescript,我的app.js是- app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' }, { id: 99, title: 'temporibus sit alia
app.js
是-
app.get('/post', (req,res) =>{
let data =
[{
userId: 10,
id: 98,
title: 'laboriosam dolor voluptates',
body: 'doloremque ex facilis sit sint culpa{ userId: 10'
},
{
id: 99,
title: 'temporibus sit alias delectus eligendi possimus magni',
body: 'quo deleniti praesentium dicta non quod'
}];
res.status(200).json(data);
});
我的my.service.ts
是-
export class MyService {
constructor(private http: HttpClient) { }
fetchData(): any {
console.log('reaches');
return this.http.get('/post').pipe(
map((post) => {
console.log(post.json());
return post.json();
})
);
}
}
export class SemComponent implements OnInit {
posts: any = [];
constructor(private myService: MyService) { }
ngOnInit() {
console.log('reaches');
this.myService.fetchData().subscribe(posts => {
this.posts = posts;
console.log(posts);
});
}
}
export const myRoutes: Routes = [
{
path: 'post',
component: SemComponent
}]
我的sem.component.ts
是-
export class MyService {
constructor(private http: HttpClient) { }
fetchData(): any {
console.log('reaches');
return this.http.get('/post').pipe(
map((post) => {
console.log(post.json());
return post.json();
})
);
}
}
export class SemComponent implements OnInit {
posts: any = [];
constructor(private myService: MyService) { }
ngOnInit() {
console.log('reaches');
this.myService.fetchData().subscribe(posts => {
this.posts = posts;
console.log(posts);
});
}
}
export const myRoutes: Routes = [
{
path: 'post',
component: SemComponent
}]
而我的路线
是-
export class MyService {
constructor(private http: HttpClient) { }
fetchData(): any {
console.log('reaches');
return this.http.get('/post').pipe(
map((post) => {
console.log(post.json());
return post.json();
})
);
}
}
export class SemComponent implements OnInit {
posts: any = [];
constructor(private myService: MyService) { }
ngOnInit() {
console.log('reaches');
this.myService.fetchData().subscribe(posts => {
this.posts = posts;
console.log(posts);
});
}
}
export const myRoutes: Routes = [
{
path: 'post',
component: SemComponent
}]
这是我获取json数据的方法
当我运行url时:“localhost:3000/post”
它没有到达我的service.ts代码
它直接显示app.js
文件中的json数据
您正在同一端口和上下文上运行web服务器(app.js)和angular应用程序。您应该尝试更改其中一个的端口号和上下文('/post') 冲突在这里,路由器路径和app.js请求上下文为“post”
请检查应用程序的端口和上下文,它应该可以解决问题。控制台上是否显示任何错误?我希望您的服务具有
@Injectable()
装饰器?@AnkitSharma不,控制台中没有任何内容我只是想知道如果您在3000上运行Node.js服务器,它如何影响您的service.ts。您是在4200还是3000上运行angular应用程序?同时点击this.http.get('/post')
也会点击同一个域并将/post
附加到它。因此,如果您在4200上运行angular,则URL的格式将为http://localhost:4200/post
@AnkitSharma我在3000上运行nodejs服务器,你在哪里运行Angular应用程序?你能用postman之类的工具访问你的后端并检查你是否从中获得任何数据吗?显然,我的代码中的“url”应该更改为您的后端url。请参见上文,我已经更新了我的查询并添加了获取结果的图像。