Casting a type (interface) via map to observable

后端 未结 3 1095
野的像风
野的像风 2020-12-19 05:11

I\'ve been learning TypeScript with Angular. And currently I stuck as this moment. Previously I used subscribed method and everything works flawlessly, but not I decided to

相关标签:
3条回答
  • 2020-12-19 05:39

    Given that your rest service or provider returns a Restaurant in this format (i've always used classes not interfaces, sorry i can't provide any help with this distinction, so in my example Restaurant is a class).

    export class Restaurant { 
        _id: string; 
        name: string; 
        description: 
        string; email: 
        { 
            address: string; 
            confirmation_code: string;
             confirmed: boolean; 
        }; 
        auth: { 
            password: string; 
        }; 
        branches: Branch[];
        menus: Menu[];
        images: File[];
        cuisines: Cuisine[];
        blocked: boolean;
        created: Date;
        business_hours: object; 
    }
    

    You should be able to have angular serialise the response for you as an example:

    getRestaurant(): Observable<Restaurant> {
      return this.http.get<Restaurant>(environment.api + "/restaurant");
    }
    

    That is given you also have a also imported the other types Branch, Menu, File, Cuisine into the typescript file containing the restaurant. for example branch would look like

    export class Branch {
       // branches properties
    }
    
    0 讨论(0)
  • 2020-12-19 05:42

    The Angular async template pipe subscribes to the Observable, that is how it is able to access the restaurant object and its properties in the template.

    If you want to access to these same thing in the component controller then you need to make a subscription in the component controller.

    0 讨论(0)
  • 2020-12-19 05:50

    Why not directly return an Observable<restaurant> from your service?

    getRestaurant(): Observable<restaurant> {
      return this.http.get<responseFormat>(environment.api + "/restaurant")
        .map((response: responseFormat) => response.data as restaurant);
    }
    

    Then on component side:

    getRestaurant() {
      this.restaurantProvider.getRestaurant().subscribe((res: restaurant) => {
        this.restaurant = res;
      });
    }
    

    The error handling (success flag, HTTP errors, etc) could be handled via an HTTP Interceptor.

    0 讨论(0)
提交回复
热议问题