Angular6 :Property catch does not exist - node.js

I am new to Angular and I have basic knowledge of it. I want to learn HttpClient so I can create a json file instead of real server. I created a service and imported HttpClient:
service.ts
import { Injectable } from '#angular/core';
import {HttpClient, HttpErrorResponse} from '#angular/common/http';
import {IEmployee} from "../../../service/src/app/employee";
import {Observable} from "rxjs/index";
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
In my class EmployeeService I have created a method for getting data from json file:
#Injectable({
providedIn: 'root'
})
export class EmployeeService {
private _url: string = "/assets/data/employees.json";
constructor(private http:HttpClient) { }
getEmployee():Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this._url)
.catch(this.errorHandler);
}
errorHandler(error: HttpErrorResponse) {
return Observable.throw(error.message || "Server Error")
}
}
But in getEmployee method I got these errors:
ERROR in ./src/app/employee.service.ts
Module not found: Error: Can't resolve 'rxjs/add/observable/throw' in 'E:\Tutorial\NodeJS\WebstormProjects\Angular\http\src\app'
ERROR in ./src/app/employee.service.ts
Module not found: Error: Can't resolve 'rxjs/add/operator/catch' in 'E:\Tutorial\NodeJS\WebstormProjects\Angular\http\src\app'
i 「wdm」: Failed to compile.
As you can see I have imported throw and catch operator but I do not know why I keep getting errors.
The other problem is, below throw method appear a line because of deprecated(Deprecated symbol used, consult docs for better alternative)!!
What is the alternative?
Angular CLI: 6.0.1
Node: 10.0.0
OS: win32 x64
Angular:
...
Package Version
------------------------------------------------------
#angular-devkit/architect 0.6.1
#angular-devkit/core 0.6.1
#angular-devkit/schematics 0.6.1
#schematics/angular 0.6.1
#schematics/update 0.6.1
rxjs 6.1.0
typescript 2.7.2
****************** EDIT ***************
I want to use builtin Observable in Angular yet and i do not want to use RXJS third party lib for angular.
This is my node module rx folder and you can see observable file in it.
And in node_modules\rxjs\operator folder there are throw and catch file..
But why it wants to search these files into E:\Tutorial\NodeJS\WebstormProjects\Angular\http\src\app folder that is make a error?

I fixed my problem by installing :
npm install --save rxjs#6 rxjs-compat#6
and use this path for rxjs:
import {Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, throwError} from 'rxjs';
import {catchError} from "rxjs/internal/operators";
Seems catch depricated at angular 6 so in order to i have used catchError like below :
getEmployee():Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this._url)
.pipe(
catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error.message || "Server Error")
}
And all errors gone now :-)

These below references are enough for you. remove unwanted references
import { Injectable } from '#angular/core';
import {HttpClient, HttpErrorResponse} from '#angular/common/http';
import {IEmployee} from "../../../service/src/app/employee";
import {Observable} from "rxjs/Observable";
Where,
removed these below references
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
And changed "rxjs/Observable" ainstead of "rxjs/index";
Update:
Should check your rxjs folder having these files, if not, then your package has missed something. you need re-install it.

Import these References
import { throwError, Observable } from 'rxjs';
import {throwError as observableThrowError} from 'rxjs';
import {catchError} from 'rxjs/operators'
and then change your code below as
getEmployees():Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this._url).pipe(
catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return observableThrowError(error.message ||"server error");
}
https://www.youtube.com/watch?v=ScaKGrW5s0I&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=31
if you still not understand check above video link

ErrorObservable creates an Observable that emits no items to the Observer and immediately emits an error notification.
Just import like this
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
And create error
ErrorObservable.create('error');

Related

#apollo/client using svelte "Named export 'remove' not found."

Like this problem, same error is occurring while using svelte kit.
here is the error:
import { remove } from "ts-invariant/process/index.js";
^^^^^^
SyntaxError: Named export 'remove' not found. The requested module 'ts-invariant/process/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'ts-invariant/process/index.js';
const { remove } = pkg;
I'm using the current version(^3.5.10) of #apollo/client, and using the beta version(^3.6.0-beta.6) gets other error; while using import { ApolloClient, InMemoryCache, gql } from '#apollo/client/core/index.js', it gets:
Directory import '/node_modules/#apollo/client/core' is not supported resolving ES modules imported from /node_modules/svelte-apollo/dist/svelte-apollo.js
or if I use import { ApolloClient, InMemoryCache, gql } from '#apollo/client/core', it gets:
Directory import 'node_modules/#apollo/client/core' is not supported resolving ES modules imported from node_modules/svelte-apollo/dist/svelte-apollo.js
Did you mean to import #apollo/client/core/core.cjs?
or if I use import { ApolloClient, InMemoryCache, gql } from '#apollo/client/core/core.cjs' it just says
exports is not defined

How to fix "× TypeError: Object(...) is not a function"?

I'm making a netflix clone app in nodejs and got stuck on generateMedia function.
On TabContentOne.js file, On import { generateMedia } from 'react-media-query' it is dotted and when I run npm install #types/react-media-query it gives me errors. I did npm i react-media-query.
import React from 'react';
import styled from 'styled-components';
import { Button } from './Button';
import { generateMedia } from 'react-media-query'
// Media Query
const customMedia = generateMedia({
smDesktop: '1440px',
tablet: '960px'
})
This is the link from my bitbucket https://bitbucket.org/danclaudiu95/nodejs-reactjs.git
I'm expecting to use generateMedia function the put style on some elements in my application but the npm server doesn't start anymore.
I recommend using another package that does the same thing, "react-media-query" is outdated and removed from github.

Connection "default" was not found - TypeORM, NestJS and external NPM Package

I'm using NestJs to create a couple of applications and I want to move the code from a NestInterceptor for an external NPM Package so I can use the same interceptor in multiple applications.
The problem is that the same code that works when used "locally" just stop working when moved to the external package.
Here's the code for the interceptor:
import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '#nestjs/common'
import { map } from 'rxjs/operators'
import { getManager } from 'typeorm'
import jwt_decode from 'jwt-decode'
#Injectable()
export class MyInterceptor implements NestInterceptor {
entity: any
constructor(entity: any) {
this.entity = entity
}
async intercept(context: ExecutionContext, next: CallHandler): Promise<any> {
const request = context.switchToHttp().getRequest()
const repository = getManager().getRepository(this.entity)
return next.handle().pipe(map((data) => data))
}
}
Here's a given controller:
import { myInterceptor } from "../src/interceptors/interceptor.ts";
#UseInterceptors(new CompanyIdInterceptor(User))
export class UserController {
}
This works fine, but if a move the file to an external NPM package and import from it like this:
import { myInterceptor } from "mynpmpackage";
I get the following error:
[Nest] 24065 - 04/18/2019, 10:04 AM [ExceptionsHandler] Connection "default" was not found. +26114ms
ConnectionNotFoundError: Connection "default" was not found.
at new ConnectionNotFoundError (/home/andre/Services/npm-sdk/src/error/ConnectionNotFoundError.ts:8:9)
at ConnectionManager.get (/home/andre/Services/npm-sdk/src/connection/ConnectionManager.ts:40:19)
Any ideas, on what causes this and how to solve it?
This might not be your problem exactly, but I had a similar problem when moving things to external packages with TypeORM. Make sure all packages from parent project are using the same version of the TypeORM package.
In my case, using yarn why typeorm showed me two different versions were being installed. One of them was used to register the entities, while the framework connected to the SQL database using another version, generating this clash.
Check your versions using yarn why [pkg-name] or if you're using NPM, try npx npm-why [pkg-name] or install globally from https://www.npmjs.com/package/npm-why.
After verifying TypeOrm versions is same in both the packages i.e- external package and consumer repository as mentioned by #Luís Brito still issue persist then issue could be-
Basically when we create an external package - TypeORM tries to get the "default" connection option, but If not found then throws an error:
ConnectionNotFoundError: Connection "default" was not found.
We can solve this issue by doing some kind of sanity check before establishing a connection - luckily we have .has() method on getConnectionManager().
import { Connection, getConnectionManager, getConnectionOptions,
createConnection, getConnection, QueryRunner } from 'typeorm';
async init() {
let connection: Connection;
let queryRunner: QueryRunner;
if (!getConnectionManager().has('default')) {
const connectionOptions = await getConnectionOptions();
connection = await createConnection(connectionOptions);
} else {
connection = getConnection();
}
queryRunner = connection.createQueryRunner();
}
Above is a quick code-snippet which was the actual root cause for this issue but If you are interested to see complete working repositories (different example) -
External NPM Package :
Git Repo : git-unit-of-work (specific file- src/providers/typeorm/typeorm-uow.ts)
Published in NPM : npm-unit-of-work
Consumer of above package : nest-typeorm-postgre (specific files- package.json, src/countries/countries.service.ts & countries.module.ts)

cant import createBatchingNetworkInterface from apollo-client

I am trying to integrate graphql with my vue project.
I am following these instructions: https://github.com/Akryum/vue-apollo
I have npm installed 'apollo-client' as required, but for some reason i can't import 'createBatchingNetworkInterface'.
this is my main.js file:
import Vue from 'vue'
import { ApolloClient, createBatchingNetworkInterface } from 'apollo-client'
import VueApollo from 'vue-apollo'
import App from './App'
import router from './router'
and this is the index.d.ts file of my apollo-client:
export { print as printAST } from 'graphql/language/printer';
export { ObservableQuery, FetchMoreOptions, UpdateQueryOptions, ApolloCurrentResult } from './core/ObservableQuery';
export { WatchQueryOptions, MutationOptions, SubscriptionOptions, FetchPolicy, FetchMoreQueryOptions, SubscribeToMoreOptions, MutationUpdaterFn } from './core/watchQueryOptions';
export { NetworkStatus } from './core/networkStatus';
export * from './core/types';
export { ApolloError } from './errors/ApolloError';
import ApolloClient, { ApolloClientOptions } from './ApolloClient';
export { ApolloClientOptions };
export { ApolloClient };
export default ApolloClient;
I don't see here the 'createBatchingNetworkInterface' desired object.
I don't know what am i doing wrong here.
It sounds like you're using Apollo Client 2.0.You should downgrade to an older version (1.9.3) to continue using network interfaces, including the batching one.
The newest version of the client uses Links instead. You can check out the upgrade guide here if you are interested. you can still batch requests in 2.0 using apollo-link-batch-http.

node-forge import in angular 2 service

I am trying to use Forge (https://github.com/digitalbazaar/forge) in my Angular 2 project.
I ran the following command :npm install node-forge
This command created the node-forge directory in my application (in the node-modules directory).
I added the node-forge reference in my package.json file: "node-forge": "0.6.39" (dependencies section).
Now, i want to import the node-forge dependency in my angular 2 service (typescript file) with the following code:
import { Injectable } from '#angular/core';
import { Forge } from 'node-forge';
#Injectable()
export class HashPasswordService {
constructor() {}
buildHash(input: string) {
var hmac = forge.hmac.create();
hmac.start('sha512', input);
hmac.update(input);
return hmac.digest().toHex();
}
}
but the import does not work : import { Forge } from 'node-forge'; and i have the following errors in the console (ng serve command):
hash-password.service.ts (2, 23): Cannot find module 'node-forge'.
hash-password.service.ts (11, 16): Cannot find name 'forge'.
So, someone know how i can import this node-forge dependency (use a npm package)? Do I miss a step in my process ?
Thanks for your help !
Just import * as forge from 'node-forge', that's it.
You need the typescript definitions as well as the npm package..
I'm not sure if this package has a DefinitelyTyped package so you can try
npm install typings -g
typings install node-forge
If this doesn't work try:
import { Injectable } from '#angular/core';
declare var Forge: any;
#Injectable()
export class HashPasswordService {
private forge: any;
constructor() {
this.forge = new Forge();
}
buildHash(input: string) {
var hmac = forge.hmac.create();
hmac.start('sha512', input);
hmac.update(input);
return hmac.digest().toHex();
}
}
Install these two packages
npm install node-forge
npm install #types/node-forge
and import * as forge from 'node-forge', that's all...You are good to go.
This is because 'node-forge' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export.
The following works for me:
import pkg from 'node-forge';
const {pkcs5, cipher, util} = pkg;

Resources