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

角度HTTP GET

  •  -3
  • Lucass  · 技术社区  · 6 年前
    1. 我有一个服务器在运行“本地主机:3000". 它以JSON格式显示数据,例如“localhost:300/个位置".
    2. “我的”数据服务.ts“包括以下代码:

    path: string = 'http://localhost:3000'
    constructor(private http: HttpClient) { }
    
    // Locations
    getAllLocations(): Observable<Location[]> {
      let location = null;
      this.http.get(this.path + '/locations')
        .map((res => location = res))
        .catch((error: any) => Observable.throw(console.log(error)));
      return location;
    }
    1. 在我的结果.component.ts我正在运行以下代码:

    constuctor(private dataservice: DataService) { }
    
    ngOnInit() {
      console.info(this.dataservice.getAllLocations());
    }

    我希望将所有位置作为JSON输出,而不是输出为“null”。

    有没有人对如何使它正常工作有什么建议?

    更新: 还尝试了以下HTTP调用:

    getAllLocations(): Observable<Location[]> {
      this.http.get<Location[]>(this.path + '/locations')
        .pipe(
          tap(items => console.info('fetched items'))
        );  
    }
    不幸的是,这段代码的输出是:“Object{u isScalar:false,source:{…},operator:{…}”
    2 回复  |  直到 6 年前
        1
  •  1
  •   plvice    6 年前

    您必须从服务返回Observable:

    path: string = 'http://localhost:3000'
    constructor(private http: HttpClient) { }
    
    // Locations
    getAllLocations(): Observable<Locations[]> {
      return this.http.get(this.path + '/locations')
        .map((res => location = res))
        .catch((error: any) => Observable.throw(console.log(error)));
    }
    

    并在组件中订阅它。

    constructor(private dataservice: DataService) { }
    
    ngOnInit() {
      this.dataservice.getAllLocations().subscribe(result => {
          console.log(result);
       })
    }
    
        2
  •  1
  •   Edric Prince Bansal    6 年前

    HttpClient#get 返回一个 Observable ? 你可以把钱还回去 get

    其次,您可以为该方法设置一个接口,以便它将返回类型化的JSON。

    最后,可以在API URL中使用模板文本。

    /**
     * Retrieves a list of locations.
     * (TODO: Add better documentation here)
     */
    getAllLocations(): Observable<Location[]> {
      return this.http.get<Location[]>(`${this.path}/locations`);
    }
    

    constuctor(private dataservice: DataService) { }
    
    ngOnInit() {
      this.dataservice.getAllLocations().subscribe(result => {
        console.log(result);
      });
    }