No provider for ConnectionBackend - (angular2 and springBoot) - spring

i'm trying to connect my spring boot project as my back-end using angular 2 as front-end.
based on web-service my back-end provide an API which present on JSON, then from here i'm building my front-end then 'm try to consume Restful service.
eventually, no component in running, a blank page displayed with three error on my web browser said:
error 1:
ERROR Error: No provider for ConnectionBackend!
at injectionError (core.es5.js:1169)
at noProviderError (core.es5.js:1207)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._throwOrNull (core.es5.js:2649)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._getByKey (core.es5.js:2620)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_.get (core.es5.js:2489)
at resolveNgModuleDep (core.es5.js:9475)
at NgModuleRef_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.NgModuleRef_.get (core.es5.js:10557)
at resolveDep (core.es5.js:11060)
at createClass (core.es5.js:10916)
error 2:
AppComponent_Host.html:1 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 1, nodeDef: Object, elDef: Object, elView: Object}
error 3:
Unhandled Promise rejection: No provider for ConnectionBackend! ; Zone: <root> ; Task: Promise.then ; Value: Error: No provider for ConnectionBackend!
at injectionError (core.es5.js:1169)
at noProviderError (core.es5.js:1207)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._throwOrNull (core.es5.js:2649)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._getByKey (core.es5.js:2620)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_.get (core.es5.js:2489)
at resolveNgModuleDep (core.es5.js:9475)
at NgModuleRef_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.NgModuleRef_.get (core.es5.js:10557)
at resolveDep (core.es5.js:11060)
at createClass (core.es5.js:10916) Error: No provider for ConnectionBackend!
at injectionError (http://localhost:4200/vendor.bundle.js:33285:90)
at noProviderError (http://localhost:4200/vendor.bundle.js:33323:12)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor.bundle.js:34765:19)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor.bundle.js:34804:25)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_._getByKey (http://localhost:4200/vendor.bundle.js:34736:25)
at ReflectiveInjector_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.ReflectiveInjector_.get (http://localhost:4200/vendor.bundle.js:34605:21)
at resolveNgModuleDep (http://localhost:4200/vendor.bundle.js:41591:25)
at NgModuleRef_.webpackJsonp../node_modules/#angular/core/#angular/core.es5.js.NgModuleRef_.get (http://localhost:4200/vendor.bundle.js:42673:16)
at resolveDep (http://localhost:4200/vendor.bundle.js:43176:45)
at createClass (http://localhost:4200/vendor.bundle.js:43032:35)
anyway guessing my back-end just gonna give as only one list in the other hand the angular2 project just gonna list all att names from the list provided by spring boot.
here my Angular code:
app.component.ts
import { NgFor } from '#angular/common';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
template: `<h1>Consumming a restful Webservice using angular 2</h1>
<ul>
<li #ngFor="item of personsLst">
{{item.id}}
</li>
</ul>`,
providers: [Http]
})
export class AppComponent {
personsLst: Array<string> = [];
theDataSource: Observable<string>;
constructor(private http: Http) {
this.theDataSource = this.http.get('/persons/dolist')
.map(res => res.json());
}
ngOnInit() {
// get the data from the rest service
this.theDataSource.subscribe(
data => {
if (Array.isArray(data)) {
this.personsLst = data;
}else {
this.personsLst.push(data);
}
},
err =>
console.log('can not get the persons list. Error code: %s, URL: %s', err.status, err.url),
() => console.log('Person(s) retrieved')
);
}
}
Note: i'm using the angular command line interface in this project!!

Related

Running Nestjs version 9 with Graphql and apollo server v4 gives Error: Cannot find module 'apollo-server-core'

I am trying to build a nestjs graphql with federation Schema with schema first approach monorepo of two microservices AUTH and LEDGER and a GATEWAY the AUTH microservice appModule.ts looks like this:
import { AuthModule } from './../auth/auth.module';
import { Module } from '#nestjs/common';
import { GraphQLModule } from '#nestjs/graphql';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { join } from 'path';
import { ApolloFederationDriver, ApolloFederationDriverConfig } from '#nestjs/apollo';
#Module({
imports: [
GraphQLModule.forRoot<ApolloFederationDriverConfig>({
driver: ApolloFederationDriver,
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
context: ({ req }) => ({ req }),
useGlobalPrefix: true,
}),
AuthModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
However I keep getting Error: Cannot find module 'apollo-server-core'. Now I am not using apollo-server-core directly I am using apollo/server v4 and V10 of nest/graphql and nest/apollo. I also understand that nestjs v9 may not be updated to apollo/server v4. can anyone shed some light on this?...what is causing this error? is there a workaround?
At this time, nestjs is not compatible with v4. You can check this: https://github.com/nestjs/graphql/issues/2445

Nestjs Hybrid application websocket + microservice

I have a problem with Nestjs, with starting a microservice that listens to a messagebroker, while simultaneously starting a websocket server with which we can communicate with front-end clients.
So I am aware of hybrid nest applications, where the websocket gateway can be injected into the microservice. However I get errors about Nest not being able to resolve the Gateway import.
I configured the microservice in a ResultsModule, the websocket in UsersModule.
The error I get is:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the ResultsController (ResultsService, ?). Please make sure that the argument UsersGateway at index [1] is available in the ResultsModule context.
These are the relevant pieces of code:
main.js
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.RMQ,
options: {
urls: [
`amqp://${config.rabbitmq.username}:${config.rabbitmq.password}#${config.rabbitmq.host}:${config.rabbitmq.port}`,
],
queue: config.rabbitmq.channelListen,
noAck: false,
queueOptions: {
durable: false,
},
},
});
await app.startAllMicroservices();
await app.listen(82);
}
bootstrap();
app.module.ts
#Module({
imports: [UsersModule, ResultsModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
results.module.ts
#Module({
imports: [UsersModule],
controllers: [ResultsController],
providers: [ResultsService],
})
export class ResultsModule {}
users.module.ts
#Module({
providers: [UsersGateway, UsersService],
})
export class UsersModule {}
users.gateway.ts
import {
WebSocketGateway,
SubscribeMessage,
MessageBody,
OnGatewayInit,
OnGatewayConnection,
OnGatewayDisconnect,
WebSocketServer,
ConnectedSocket,
} from '#nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
#WebSocketGateway(82)
export class UsersGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
constructor(private readonly usersService: UsersService) {}
#WebSocketServer() server: Server;
afterInit(server: Server) {
console.log('init');
}
handleDisconnect(client: Socket) {
console.log(`Client disconnected: ${client.id}`);
}
handleConnection(client: Socket, ...args: any[]) {
console.log(client.id);
}
#SubscribeMessage('resource')
create(
#MessageBody() createUserDto: CreateUserDto,
#ConnectedSocket() client: Socket,
) {
console.log(client.id);
console.log(createUserDto.resourceId)
}
}
I tried to move around the imports, not wrapping the gateway in a module.
Tried moving the results module out of the app.module. Which removes the error, however then I do not understand where to let nestjs know to use the resultsmodule for the microservice.
------------------------ANSWER-------------------------------------
Alright, we fixed it with the help of #yomateo , we were missing the export of the websocket gateway in the module. Thanks for the help!
You're close (you have it backwards).
Have your UsersGateway or UsersService call the ResultsService.

Nestjs displays error during production that: "Persisted queries are enabled and are using an unbounded cache."

Nestjs application does not display the error message during development only during production. I found no module where the apollo -server can be configured to cache: "bounded". The Nestjs documentation itself makes no mention of it anywhere.
The complete error message says:
Persisted queries are enabled and are using an unbounded cache. Your server is vulnerable to denial of service attacks via memory exhaustion. Set cache: "bounded" or persistedQueries: false in your ApolloServer constructor, or see https://go.apollo.dev/s/cache-backends for other alternatives.
Here are some dependencies I suspect could be related to it.
"#nestjs/apollo": "10.0.19",
"#nestjs/common": "9.0.5",
"#nestjs/core": "9.0.5",
"#nestjs/graphql": "10.0.20",
A similar issue was opened at github and sadly it was closed without any solution.
This is related to the Apollo module's configuration, by default the cache is "unbounded" and not safe for production (see : https://www.apollographql.com/docs/apollo-server/performance/cache-backends/#ensuring-a-bounded-cache)
You can easily follow their recommendation by adding the optional "cache" configuration inside your GraphQL module.
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
cache: 'bounded', // <--- This option
...
}
Or provide an external caching with KeyvAdapter see: https://github.com/apollographql/apollo-utils/tree/main/packages/keyvAdapter#keyvadapter-class
In the app.module.ts inside the import array,
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
useClass: GqlConfigService,
}),
Then in the GqlConfigService I add cache: 'bounded' in the ApolloDriverConfig options.
import { ConfigService } from '#nestjs/config';
import { ApolloDriverConfig } from '#nestjs/apollo';
import { Injectable } from '#nestjs/common';
import { GqlOptionsFactory } from '#nestjs/graphql';
import { GraphqlConfig } from './config.interface';
#Injectable()
export class GqlConfigService implements GqlOptionsFactory {
constructor(private configService: ConfigService) {}
createGqlOptions(): ApolloDriverConfig {
const graphqlConfig = this.configService.get<GraphqlConfig>('graphql');
return {
// schema options
cache: 'bounded', // ! <== Added here
autoSchemaFile: graphqlConfig.schemaDestination || './src/schema.graphql',
sortSchema: graphqlConfig.sortSchema,
buildSchemaOptions: {
numberScalarMode: 'integer',
},
// subscription
installSubscriptionHandlers: true,
debug: graphqlConfig.debug,
playground: graphqlConfig.playgroundEnabled,
context: ({ req }) => ({ req }),
};
}
}

How to use useI18n inside vue3 composition api?

I'm using vue-i18n in conjunction with quasar + vue 3 composition api but I get an error as following
SyntaxError: 19 vendor.49822a76.js:formatted:926 SyntaxError: 19 (at vendor.49822a76.js:formatted:27825:21)
at F (vendor.49822a76.js:formatted:27825:21)
at Pt (vendor.49822a76.js:formatted:29590:20)
at vn (vendor.49822a76.js:formatted:30617:27)
at 238.35491042.js:1:419
at f (vendor.49822a76.js:formatted:883:25)
at p (vendor.49822a76.js:formatted:892:27)
Error In console when using useI18n
and here is my i18n file:
Boot directory:
import { boot } from 'quasar/wrappers'
import { createI18n } from 'vue-i18n'
import messages from 'src/i18n'
export default boot(({ app }) => {
const i18n = createI18n({
locale: 'ar',
messages
})
// Set i18n instance on app
app.use(i18n)
})
My Vue File
import { useI18n } from 'vue-i18n';
import AppService from "../../services/api";
export default defineComponent({
setup() {
const { t } = useI18n();
console.log(t)
}
})
any clue?
You need specify allowComposition: true to createI18n options.
Here is the link to the documentaion

.NET Core + Angular-CLI App - can't pass data from api to components [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm building an ASP .NET Core App with Angular-CLI using this tutorial.
App works great, I got pre-build event to ng build before starting the app in VS, it works OK. I also can successfully get to my API over localhost:port/api/[controller] (in this case it would be Contacts as it's supposed to be a contact book).
Now, I'm trying to have Angular get the data directly from API. For this reason, I created a IContact interface, a ContactService and I pass it onto ContactComponent which is supposed to display it.
I might be making a silly mistake here (my skills are very basic), but for some reason I don't even see the object .json coming in through the network logs when I run the app (before trying to pass it to the view I'm trying to ensure I'm getting the data from the API first).
I might be doing something wrong (so I encourage you to reply even if you think you might be saying silly-obvious stuff) but here's my questions:
Should my code below work (not attaching imports though, I think I got all of them but check me ;-))? I'm not talking super-efficient or stuff, just basic to get the job done.
What is the best way to see if service to getAPI is working? Would that be network logging in your browser if you just import the service into the component and try to call the get method? Or is there another way?
Is my logic and approach towards the general architecture of the app OK or am I getting something wrong? :-)
contact.service.ts
const API_URL = environment.apiUrl;
#Injectable()
export class ContactService {
constructor(private http: Http) { }
public getContacts(): Observable<IContact[]> {
return this.http.get(API_URL)
.map((response: Response) => <IContact[]>response.json())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error')
}
}
icontact.ts
export interface IContact {
id: number;
firstName: string,
lastName: string,
address: string,
telephone: string
}
contact.component.ts
#Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css'],
providers: [ContactService]
})
export class ContactComponent implements OnInit {
private _contactService: ContactService;
private contactlist: IContact[];
constructor() {
}
public ngOnInit() {
this._contactService.getContacts()
.subscribe((contacts) => { this.contactlist = contacts });
}
}
Any other code requirements or anything - let me know. All feedback is appreciated. Thanks!
I have slightly changed your code.
File icontact.ts. I have made IContact a simple type. You can make it an interface back to support your object shape.
export type IContact = string;
File contact.service.ts. We call the /api/values API that is created by default in a new ASP.NET Core Web API project if you follow the tutorial you mentioned.
import { Injectable } from "#angular/core";
import { Http } from "#angular/http";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map'
import { IContact } from "./icontact";
const API_URL = '/api/values'; // environment.apiUrl;
#Injectable()
export class ContactService {
constructor(private http: Http) { }
public getContacts(): Observable<IContact[]> {
return this.http.get(API_URL)
.map(response => <IContact[]>response.json());
}
}
File contact.component.ts. The template simply displays the list.
import { Component, OnInit } from "#angular/core";
import { ContactService } from "./contact.service";
import { IContact } from "./icontact";
#Component({
selector: 'app-contact',
template: '<div *ngFor="let contact of contactList">{{contact}}</div>',
providers: [ContactService]
})
export class ContactComponent implements OnInit {
private contactList: IContact[];
constructor(private contactService: ContactService) { }
public ngOnInit() {
this.contactService.getContacts().subscribe(
(contacts) => { this.contactList = contacts; },
(error) => { console.log(error); }
);
}
}
File app.component.html. Display your component on the application's page.
<app-contact>Wait...</app-contact>
File app.module.ts. Import HttpModule. That fixes one of the error messages on your screenshot.
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { ContactComponent } from "./contact.component";
#NgModule({
declarations: [AppComponent, ContactComponent],
imports: [BrowserModule, HttpModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In the Configure method in Startup.cs, make sure you put the app.Use(...) call before app.UseStaticFiles().
Since you serve your Angular app from wwwroot by a ASP.NET Core middleware, the host is the same for the Angular app and the Web API, so you don't need to configure CORS for that setup.
By the way, you may be interested in taking a look at the Angular CLI Templates on Visual Studio Marketplace. (Disclaimer: I'm the author.) The Item Template supports your project setup out-of-the-box.

Resources