我在这里将角度6与角度材料一起使用,并且试图构建一个将graphQL与Apollo结合使用的搜索组件。
好,该组件正常工作,但是我想解决以下问题:
与graphQL服务器交互的我的产品服务:
import { Injectable } from '@angular/core';
import {Apollo} from 'apollo-angular';
import gql from 'graphql-tag';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private apollo: Apollo) { }
searchForProduct(productName: string) {
return this.apollo.watchQuery<any>({
query: gql`{products_by_p_name_search(lang_id:1,query:"${productName}")
{category_id,price,category_name,id,name,desc,quantity,year_manufacture,image_file}}`
});
}
}
带有mat-autocomplete
组件的我的搜索组件html:
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="חפש מוצר" aria-label="חפש מוצר" [matAutocomplete]="auto" [formControl]="productCtrl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let product of products" [value]="product.name">
<img class="example-option-img" aria-hidden src="../../assets/products/{{product.id}}/{{product.imgFile}}_t.jpg" height="25">
<span>{{product.name}}</span> |
<small>Population: {{product.population}}</small>
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
最后是我的搜索组件(Typescript文件):
import { Component, OnInit } from '@angular/core';
import {FormControl} from '@angular/forms';
import {Product} from '../product';
import {ProductService} from '../product.service';
@Component({
selector: 'app-search-product',
templateUrl: './search-product.component.html',
styleUrls: ['./search-product.component.scss']
})
export class SearchProductComponent implements OnInit {
productCtrl = new FormControl();
products: Product[] = [];
constructor(private productService: ProductService) {
}
ngOnInit() {
this.productCtrl.valueChanges
.subscribe(v => {
this.productService.searchForProduct(v.toString()).valueChanges.subscribe(
({data}) => {
const productsResult: Product[] = [];
data.products_by_p_name_search.forEach((productObj) => {
const product = new Product();
product.id = productObj.id;
product.categoryName = productObj.category_name;
product.name = productObj.name;
product.desc = productObj.desc;
product.quantity = productObj.quantity;
product.yearManufacture = productObj.year_manufacture;
product.imgFile = productObj.image_file;
product.categoryId = productObj.category_id;
product.price = productObj.price;
productsResult.push(product);
});
this.products = productsResult;
});
});
}
}
据我所知,这些代码行可以工作,但它可能不是最优化的编写方式。因此,非常感谢您提供有关上述问题的任何信息。