Reputation: 15283
I intergrated angular18
with apollo-angular
. when i try to fetch the call from gihub.com
the network call hangs on pending
state.
here is my provider for apollo-angular
:
import { ApplicationConfig, inject } from "@angular/core";
import { ApolloClientOptions, ApolloLink, InMemoryCache } from "@apollo/client/core";
import { setContext } from "@apollo/client/link/context";
import { Apollo, APOLLO_OPTIONS } from "apollo-angular";
import { HttpLink } from "apollo-angular/http";
export const githubData = {
token: "ghp_M4T0mxxxxxxxUqnI4BHWyD6dGmQLk3Fovcb",
};
const uri = "https://api.github.com/graphql";
const header = setContext((operation, context) => ({
headers: {
Accept: "charset=utf-8",
},
}));
const auth = setContext((operation, context) => {
const token = localStorage.getItem("token");
if (token === null) {
return {};
} else {
return {
headers: {
Authorization: "bearer " + githubData["token"],
},
};
}
});
export function apolloOptionsFactory(): ApolloClientOptions<any> {
const httpLink = inject(HttpLink);
const link = ApolloLink.from([header, auth, httpLink.create({ uri })]);
return {
link: link,
cache: new InMemoryCache(),
};
}
export const graphqlProvider: ApplicationConfig["providers"] = [
Apollo,
{
provide: APOLLO_OPTIONS,
useFactory: apolloOptionsFactory,
},
];
My service :
import { Injectable } from "@angular/core";
import { gql, Query } from "apollo-angular";
@Injectable({
providedIn: "root",
})
export class GitServiceService extends Query<Response> {
document = gql`
query {
user(login: "3gwebtrain") {
issues(first: 10) {
nodes {
title
body
closedAt
}
}
}
}
`;
}
my component:
import { Component, inject, OnInit } from "@angular/core";
import { RouterOutlet } from "@angular/router";
import { GitServiceService } from "./services/git-service.service";
@Component({
selector: "app-root",
standalone: true,
imports: [RouterOutlet],
templateUrl: "./app.component.html",
styleUrl: "./app.component.scss",
})
export class AppComponent implements OnInit {
gitService = inject(GitServiceService);
ngOnInit(): void {
console.log("Hellow there");
this.gitService.watch().valueChanges.subscribe((data) => console.log("data", data));
}
}
when component loads, getting network status as pending
and hanged.
Upvotes: 1
Views: 55
Reputation: 56052
This if condition will always return false, so your request is made without the auth token.
const auth = setContext((operation, context) => {
const token = localStorage.getItem("token");
if (token === null) { // <- token is never set so it will always go to if condition
return {};
} else {
return {
headers: {
Authorization: "bearer " + githubData["token"],
},
};
}
});
Also the auth token seems to be of different length, can you set the auth token Generate Auth token
Upvotes: 2