0

I am following the Angular.io guide for angular animations but have run into an error.

This is the sample code they provided.

export class Hero {
  constructor(public name: string, public state = 'inactive') { }

  toggleState() {
    this.state = this.state === 'active' ? 'inactive' : 'active';
  }
}

While testing my service, I was able to properly inject the service into my navbar component and my basic toggleState() function works. However, when I add the public state = 'inactive' text into my service constructor I get an error.

Arguments array must have arguments.

I have been reading up on services and DI and cannot find the correct articles which can explain to me how to use public constructors in a service so I can fix my error.

My current code:

navbar.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

import { SidebarService } from '../../services/sidebar.service';

@Component({
  selector: 'app-nav-bar',
  templateUrl: './nav-bar.component.html',
  styleUrls: ['./nav-bar.component.css'],      
})
export class NavBarComponent implements OnInit {
  @Input() navbarState;

  constructor(private sidebar: SidebarService) { }

  ngOnInit() {
  }

  toggleNavbar() {
    this.sidebar.toggleNavbar();
  }

sidebar.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SidebarService {

  constructor(public state = 'inactive') { }

  toggleNavbar() {
    if (this.state === 'inactive') {
    console.log('it works');
    }
  }
}

navbar.component.html

<button class="navbar-toggler" type="button" (click)="toggleNavbar()">
Cuong Vo
  • 249
  • 1
  • 6
  • 16
  • 2
    Remove the `public state = 'inactive'` from the constructor, and make it a property of the class. You can't have default parameters on the constructor of an injectable service. The constructor arguments must all be valid injectable tokens. – Reactgular Sep 15 '18 at 18:49
  • @cgTag Thanks! That did the trick, but what I dont understand is why the guide has the property inside the constructor? – Cuong Vo Sep 15 '18 at 18:54
  • 2
    The example in the guide is not an injectable service. It does not have the `@Injectable` decoration. It is just a generic TypeScript class that is used in the example. – Reactgular Sep 15 '18 at 19:01
  • 1
    Here is the full source code for the Heroes example: https://github.com/johnpapa/angular-tour-of-heroes – Reactgular Sep 15 '18 at 19:02

0 Answers0