代码之家  ›  专栏  ›  技术社区  ›  Rupesh

从nodejs获取json数据到Angular 6

  •  0
  • Rupesh  · 技术社区  · 8 年前

    我的 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();
              })
            );
          }
    }
    

    sem.component.ts 是-

    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);
        });
      }
    }
    

    还有我的 Routes 是-

    export const myRoutes: Routes = [
      {
        path: 'post',
        component: SemComponent
      }]
    

    这是我获取角度json数据的方法。

    当我运行url时:“localhost:3000/post”。

    它无法到达我的service.ts代码。

    它直接显示来自 应用程序js 文件

    image

    2 回复  |  直到 8 年前
        1
  •  0
  •   Evosoft_Germany    8 年前
    export class MyService {
      constructor(private http: HttpClient) { }
        fetchData(): Promise<any> {
          return this.http
          .get("url").toPromise()
          .then((response)=>{
            return response;
          })
          .catch((error)=>{
            console.log(error)
          })
      }
    }
    

    在SemComponent中,可以按如下方式使用返回的数据。

    export class SemComponent implements OnInit {
    posts: any = [];
    constructor(private myService: MyService) { }
        ngOnInit() {
            console.log('reaches');
            this.myService.fetchData().then(data => {
              this.posts = data;
              console.log(this.posts);
            });
        }
    }
    
        2
  •  0
  •   ntulsi    8 年前

    您正在同一端口和上下文上运行web服务器(app.js)和angular应用程序。您应该尝试更改其中一个端口号和上下文('/post')。

    冲突在这里,路由器路径和app.js请求上下文是'post'。

    请检查应用程序的端口和上下文,它应该可以解决问题。

    推荐文章