Error: Angular 6 - The 'map' operator is not available on an observable type

After updating to Angular 6, I encountered this error. While I found documentation on using .pipe(), I'm unsure how to implement it when there are multiple .map() functions as shown below. Your assistance would be greatly appreciated...

   import {Injectable} from '@angular/core';
    import {Http, Headers} from '@angular/http';
    import 'rxjs/add/operator/map';
    import {TOKEN_AUTH_PASSWORD, TOKEN_AUTH_USERNAME} from '../services/auth.constant';

    @Injectable()

    export class AuthenticationService {

      static AUTH_TOKEN = '/oauth/token';
      constructor(private http: Http) {
      }
      login(username: string, password: string) {

        const body = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;

        const headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Authorization', 'Basic ' + btoa(TOKEN_AUTH_USERNAME + ':' + TOKEN_AUTH_PASSWORD));
        return this.http.post(AuthenticationService.AUTH_TOKEN, body, {headers})
          //.map(res => res.json())
          .pipe(map((res: any) => {
            if (res.access_token) {
              return res.access_token;
            }
            return null;
          }));
      }
    }

I know how to use .pipe with a single .map function like the example below, but I am struggling with implementing pipe() when multiple .map functions are involved.

.pipe(map(data => {})).subscribe(result => {
      console.log(result);
    });

Answer №1

When using multiple operators with pipes, remember to separate them with a comma:

return this.http.post(AuthenticationService.AUTH_TOKEN, body, {headers})
.pipe(
  map(res => res.json()),
  map((res: any) => {
    if (res.access_token) {
      return res.access_token;
    }
    return null;
  })
);

However, it is unnecessary to include map(res => res.json()) in your specific scenario.

Additionally,

In previous versions, the import statement was import 'rxjs/add/operators/map'.

For Angular 6, it should now be:

import { map } from 'rxjs/operators';

Lastly, if you want to achieve the cancelling effect, consider using switchMap instead of map. Learn more here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reasoning behind ethers.js choosing to have the return value of a function be an array that contains the value, rather than just the value itself

An issue arose with the test case below: it('should access MAX_COUNT', async () => { const maxCount = await myContract.functions.MAX_COUNT(); expect(maxCount).to.equal(64); }); The test failed with this error message: ...

Error: Invalid type in tslint.json. Making sure your configuration aligns with the rules set in tslint.json

I am facing an issue where Ng serve works fine, but when I try to build the project, it gives me an error stating "type is not allowed" in tslint.json. Any suggestions on how to match the configuration with what is set up in tslint.json? ...

Separate files containing TypeScript decorators are defined within a project

(Let's dive into Typescript and Angular2, shall we?) Having primarily coded in Symfony2 with annotations, I found it convenient to configure entity mapping, routing, and other features using yaml, xml, or plain PHP. This flexibility was great for cre ...

Main Angular2 component connected to the body element

I currently have an AngularJS app that I would like to rewrite using Angular2. The original app was a mix of Asp.Net MVC with the ng-app directive in the body tag. In Angular2, I want to follow a similar approach by setting the selector for the AppCompone ...

Utilizing Solid.js: Integrating useContext inside a provider triggered by an external event

const CounterContext = createContext(); export function CounterProvider(props) { const [count, setCount] = createSignal(0), store = [ count ]; return ( <CounterContext.Provider value={store}> {props.children} </Co ...

Error displaying messages from the console.log function within a TypeScript script

My node.js application runs smoothly with "npm run dev" and includes some typescript scripts/files. Nodemon is used to execute my code: This is an excerpt from my package.json file: { "scripts": { "start": "ts-node ./src/ind ...

The Ng2AutoCompleteModule library, which contains the ng2-auto-complete module, was not correctly processed by ngcc or is not compatible with Angular Ivy

I am in the process of upgrading Angular from version 2 to 15 and encountering an error. Can anyone provide assistance with this issue? It seems that the ng2-auto-complete library, which declares Ng2AutoCompleteModule, has not been processed correctly by ...

Utilizing npm link with a TypeScript-written module: a guide for seamless development?

I am currently in the process of developing a TypeScript and Webpack-based library. To facilitate the development of this library, I have set up a separate test project (written in JS) and connected the library using npm link <package-name>. Howeve ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

struggling to implement dynamic reactive forms with Angular

Currently, I am experimenting with building a dynamic reactive form using Angular. While I have successfully implemented the looping functionality, I am facing some challenges in displaying it the way I want. <form [formGroup]="registerForm" (ngSubmit) ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

Utilizing spread operators for prop types in React

While working on a react component for displaying icons, I came across the following code: import React from "react"; import MIcon from "react-native-vector-icons/MaterialIcons"; import MaterialIconCommunity from "react-native-vect ...

Varying outcomes for identical types in TypeScript

I'm puzzled as to why TypeScript offers different suggestions for equal types (ObjType1 and ObjType2). In the first case, it suggests a union type "a" | "b" However, in the second case for the same type, it does not provide a uni ...

The map() function's splice operation unexpectedly removes only half of the array

I am currently working with an array that contains 146 objects, each object having its own unique id. My goal is to delete any objects from the array that do not have a matching id. I wrote a function to accomplish this task, however, it only works for hal ...

Customize TypeScript Generic Types in Method<T> Extending from a Base Class<T> as a Backup Plan

In my example, I have created an Angular Service with multiple Generic Types that can be overridden through the methods. The issue I am encountering revolves around = versus extends and how it affects typing in the arguments. Strangely, using = works perfe ...

Ways to access the parent value within a child component in Angular 4

I am a beginner in angular4 Currently, I am working on a Registration process that involves multiple steps. To control the visibility of these steps based on certain conditions, I am using the hide/show functionality. The Registration process consists of ...

What could be causing the angular router to load the lazy loaded module during startup?

Currently, I am facing an issue with setting up a new Angular project using Angular 7 version. I have created a CoreModule that includes components like the Login Page, Forgot Password page, etc. My intention is to have the application load app-routing.mo ...

Setting the default value for Angular Material's select component (mat-select)

Many inquiries are focused on setting a default value to display in a "Select" control. In this particular case regarding Angular 8 template driven forms, the issue lies in the inability to show the default value in the mat-select when the button is clicke ...

Web-based API for authentication system using Ionic framework and token-based login

https://i.sstatic.net/OzKkI.pngI am developing a photo-sharing app that requires a login system. However, when attempting to log in, an error occurs stating that the value is not found. I am able to retrieve the value in services but struggling to get the ...