Angular 4: Error when trying to activate route with empty route parameter: 'Attempting to provide 'null' instead of a stream...'

When accessing /my/route/8000, everything functions as expected.

However, attempting to access /my/route without any route parameters results in an error:

An error occurred: 'null' was provided instead of a stream. Ensure you provide an Observable, Promise, Array, or Iterable.

ngOnInit() {
  // the observable method
  this.route.paramMap
     .switchMap((params: ParamMap) => {
        this.number = params.get('number');
        return params.get('number');
     })
     .subscribe((number) => { return; });
}

Defined Routes

export const routes: Routes = [{
   path    : 'my',
   children: [{
      path      : '',
      pathMatch : 'full',
      redirectTo: 'route'
   },  {
      path     : 'route',
      component: SubscriberRegisterComponent, 
   }, {
      path     : 'route/:number', // captures route parameters
      component: SubscriberRegisterComponent,
   }]
}];

Why am I unable to access my route directly without providing route parameters?

By temporarily commenting out the observable method and using the no-observable method, the route can be accessed with empty parameters

  this.number = this.route.snapshot.paramMap.get('number ');

Answer №1

.switchMap() is meant to take a function that returns an Observable, but in your code you are actually returning the parameter value instead:

  this.route.paramMap
     .switchMap((params: ParamMap) => {
        this.number = params.get('number');
        return params.get('number');
     })

Using switchMap to set a class property goes against the intended use of Observables, which is to perform work inside the subscribe method (or using the .do() operators). Consider rewriting it like this:

this.route.paramMap.subscribe( (params:ParamMap) => {
    this.number = +params.get('number');
 });

If your route sometimes includes a parameter and sometimes does not, there's no need to define it twice in the route configuration! Optional parameters should not be included in the route definition. Just keep it simple:

{
  path     : 'route',
  component: SubscriberRegisterComponent, 
}

Take some time to understand how optional parameters work. They can still be accessed through paramMap. Check out the official documentation for more information.

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

Crafting a model for arrays of objects - a guide to perfection

Why am I experiencing errors in the console when trying to set the API return to a variable? How can this issue be resolved? This is my TypeScript code: public myData = new myDataModel(); getData(){ this.myCoolService.getDataAPI() .subscribe(( ...

Obtain the total number of requests submitted by the user within a 24-hour period

I have a POST request point in my API where I need to track and store all work journals made by a worker. export const registerPoint = async (req: Request, res: Response) => { const user = res.locals.decoded; const {id} = user; const point = new Point ...

Employing a provider within a different provider and reciprocally intertwining their functions

I'm currently facing an issue with two providers, which I have injected through the constructor. Here's the code for my user-data.ts file: @Injectable() export class UserDataProvider { constructor(private apiService: ApiServiceProvider) { ...

How to selectively disable options in p-dropdown using Angular Reactive Forms

Implementing PrimeNg p-dropdown in a component. <p-dropdown [options]="productRequest" formControlName="request" optionLabel="ProductName" (onChange)="someFunction('request')"> </p-dropdown> ...

What is the process for obtaining the Angular.json file for my NX Workspace?

Looking to develop a fresh Angular web application within my NX Workspace, with plans to eventually convert it for iOS and Android using Capacitor. After setting up the nx monorepo, I proceeded to generate a new Angular application by running the command ...

Utilize the Typescript model in the form of an Array structure

I have created some models and I need to use the type that will be assigned as an array. After receiving a result from an api call, I instantiate a new object of my 'type', but the result is an array. How can I make this work? When I set the var ...

Discovering whether an array is empty in Angular8 and retrieving values within a foreach loop

Here is the data that I am working with: I need to inspect the values[] array in each object and determine if it is empty. If the array is empty, I want to return true. However, if the values[] array contains some records, I should return false. I have c ...

limiting the number of HTTP requests within a JavaScript forEach loop

In my current coding situation, I am facing an issue where the HTTP requests are being made simultaneously within a forEach loop. This leads to all the requests firing off at once. const main = async () => { items.forEach(async (i: Item) => ...

Having trouble with Angular? encountering the annoying issue of 'ng command not found' and 'ng setup not persisting'?

Currently, I am in the process of working on various projects to familiarize myself with using Angular on my mid-2012 MacBook Pro running macOS Mojave 10.14.6, along with VS Code 2. While I have taken some classes previously, my coding expertise is still q ...

Utilizing MathJax in the AstroJS project to convert all [tex] code on the page into MathML code when building

In my latest project, I've implemented AstroJS as a Static Site Generator. One of the key benefits of utilizing AstroJS is its capacity to execute JS code within the --- --- code fences section of a .astro file, enabling the creation of webpages witho ...

Guide to implementing promises in Angular 2 with LoopBack

Displayed here is a project completed using the Angular2 framework with Loopback. In particular, I am looking to incorporate promises in conjunction with data retrieved via Loopback. data.component.ts ngOnInit () { this.dataService.getAllData() .then(res ...

The Angular single-page application fails to refresh when being executed via Visual Studio 2017 Community

I have encountered a problem with my angular 6 app not refreshing when running through Visual Studio 2017. The project consists of multiple projects, including a .NET Core 2 WebAPI and the angular app in question. Even after setting the startup to only be ...

Revising input value post model binding

In my scenario, I have a text input that is bound to a model property of type Date: <input type="text" [(ngModel)]="model.DateStart" ngControl="dateStart" id="dateStart" #dateStart /> The value of model.DateStart (which is of type DateTime) looks l ...

Refresh an Angular page automatically

Having a small issue in my angular application. The problem arises on the first page where I display a table listing all employees along with a "Create New Employee" button that opens a form for adding a new employee. However, after submitting the form and ...

The hierarchy of precedence when using the TypeScript Type Assertion operator

Is it necessary to wrap the js-ternary operator with 'as' Type Assertion? ios ? TouchableOpacity : View as React.ElementType Will it automatically use the result of '?:' since it comes first? Or would a better implementation be: (ios ...

User Interface showcasing real-time progress data pulled from API

Currently, I am facing a situation where there are three docker containers involved in my project: - An angular frontend - A Django backend - A Python processing API The scenario is such that a user uploads a file to the backend volume through the fronten ...

Bootstrapping Angular2 asynchronously using an external JSON configuration file

After upgrading to angular2 RC6, I am facing a challenge in loading an external JSON config file before bootstrapping my AppModule. It was working fine with RC5 but now I am struggling to find the equivalent way of injecting this data. /** Create dummy XS ...

React with Typescript: Potential occurrence of an undefined object

While working with React and TypeScript, I encountered the error Object is possibly 'undefined' when using language.toLowerCase().includes(selectedCategory). To address this issue, I implemented a check as shown below. Although this resolved th ...

What purpose does the NewableFunction interface serve?

An obscure built-in interface in TypeScript is VoidFunction, meant to represent functions that take no parameters and return void. Even more obscure is NewableFunction, which supposedly should represent functions that are "newable" or "constructable," but ...

Upgrading my loop React component from vanilla JavaScript to TypeScript for improved efficiency and functionality

After seeking assistance from Stack Overflow, I successfully created a loop in React using a functional component that works as intended. However, I am encountering errors while trying to refactor the loop to TypeScript. The code for my DetailedProduct c ...