Reputation: 415
I'm developing my first Angular v18 client app consuming an Azure function app with GraphQL (hotchocolate).
I have a problem with apollo apparently, when I try to consume the service, in the console.log
of server, I can see the consume to the Azure function correctly and the return of data:
But in the client console, it shows these errors:
Additionally I can't see the data in my components (I'm trying to show a list of products card); the list of products is always empty.
I don't know why this happens; in my .NET Azure function, I allow any origin.
My code in the Azure function:
Startup.cs
:
[assembly: FunctionsStartup(typeof(Startup))]
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.AddDatabase();
builder.Services.AddUseCases();
builder
.AddGraphQLFunction()
.AddQueryType<Query>();
// Configuración de CORS
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}
}
My client code:
graphql.provider.ts
:
import { Apollo, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { ApplicationConfig, inject } from '@angular/core';
import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core';
const uri = 'http://localhost:7071/api/graphql/';
export function apolloOptionsFactory(): ApolloClientOptions<any> {
const httpLink = inject(HttpLink);
return {
link: httpLink.create({ uri }),
cache: new InMemoryCache()
};
}
export const graphqlProvider: ApplicationConfig['providers'] = [
Apollo,
{
provide: APOLLO_OPTIONS,
useFactory: apolloOptionsFactory,
},
];
product.service.ts
:
import { Injectable, computed, signal } from '@angular/core';
import { Product } from '@core/models/product';
import { Apollo, gql } from 'apollo-angular';
interface State{
products: Product[],
error: any,
loading: boolean
}
const GET_PRODUCTS = gql`
{
productsPaginated(first: 10, after: null){
nodes{
key
name
price
sale_price
ratings
},
edges{
cursor
}
pageInfo{
hasNextPage,
endCursor
}
totalCount
}
}
`;
@Injectable({
providedIn: 'root'
})
export class ProductsService {
#state = signal<State>({
loading:true,
products: [],
error: false
});
public productsGet = computed(()=> this.#state().products);
public productsErrGet = computed(()=> this.#state().error);
constructor(private apollo : Apollo) {
this.apollo.watchQuery({
query: GET_PRODUCTS
}).valueChanges.subscribe(({data, error} : any) => {
console.log(data.productsPaginated.nodes);
const products = data.productsPaginated.nodes.map((val: any): Product => ({
key: val.key,
name: val.name,
price: val.price,
sale_price : val.sale_price,
ratings: val.ratings
}));
this.#state.set({
loading:false,
products: products,
error: error
});
})
}
}
Upvotes: 0
Views: 89