Skip to content

Query/Mutation components #1132

@chihab

Description

@chihab

Wouldn't be interesting to have Query and Mutation components as the ones we have on react-apollo ?

  • Required input: query: a GraphQL query document parsed into an AST by graphql-tag
  • Outputs: data, loading and error events
  • Render prop: projected template with context containing data, loading and error values

Basic query component usage would be (with the render prop pattern) :

<ngx-query [query]="query">
	<ng-template let-data let-loading="loading" let-error="error">
		<div *ngIf="loading">
			Loading...
		</div>
		<div *ngIf="error">
			Error :(
		</div>
		<p>
			{{ data | json }}
		</p>
	</ng-template>
</ngx-query>

where the query in the component would be:

query = gql`query getMessage {
           message {
              text
          }
}`;

and a basic implementation of the Query component (Render Prop use case) would be:

import { TemplateRef, Input, ContentChild, OnInit, ViewContainerRef, Component, AfterViewInit } from '@angular/core';
import { Apollo } from 'apollo-angular';

@Component({
  selector: 'ngx-query',
  template: `<ng-container *ngTemplateOutlet="template, context: {
    $implicit: data,
    loading: loading,
    error: error
  }"></ng-container>`
})
export class QueryComponent implements OnInit {
  @Input() query; // Should be typed
  @ContentChild(TemplateRef) template: TemplateRef<any>;

  data: any;
  loading: boolean;
  error: any;

  constructor(private apollo: Apollo) {
  }

  ngOnInit() {
    this.apollo
      .watchQuery({
        query: this.query,
      })
      .valueChanges.subscribe(result => {
        this.data = result.data;
        this.loading = result.loading;
        this.error = result.error;
      });
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions