Observable value is not updating

I am trying to use a service in Angular that holds the state of the application in a string variable. I am using RxJS to use BehaviorSubject, and then my components subscribe to an observable of the BehaviorSubject.

State.Service.ts

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


@Injectable()
export class StateService {

  private sourceState = new BehaviorSubject<string>('Default State');
  currentState = this.sourceState.asObservable();

  constructor() { }

  setState(state: string) {
    this.sourceState.next(state);
    console.log(this.currentState);
    }
}

My components all subscribe to this observable during the NgOnInit lifecycle.

Nav.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { StateService } from '../../services/state.service';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import { Location } from '@angular/common';

@Component ({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss'],
  providers: [StateService]
})
export class NavComponent implements OnInit {
  currentState: string;

  constructor(
    private authService: AuthService,
    private router: Router,
    private stateService: StateService
  ) {}

  ngOnInit() {
    this.stateService.currentState.subscribe(
      state => (this.currentState = state)
    );
  }

  logout() {
    this.authService.logout();
  }

  changeState(state: string) {
    this.stateService.setState(state);
  }
}

Other components in my application will call the setState function in the state.service.ts file. I am binding the state value in my template just to watch the value so I can then use directives to change the experience based on application state.

The Problem

Values in the components are not changing even though when I console.log the observable I can see it is being set correctly.

Note

When I call the setState function within the nav component I do see the value of the string interpolation change but only in the nav.component.ts, other components will not change. It is almost like they are using clones of the observable.

nav.component.html

<nav class="navbar" [ngClass]="{red: currentState==='stove'}">
  <a  class="navbar-brand" routerLink="/app">
    <img src="../assets/img/app/back.svg" alt="">
  </a>
  <ul class="nav justify-content-end">
    <li class="nav-item">
      <a class="nav-link active" routerLink="/login" (click)="logout()">Logout
        <i class="fa fa-sign-out" aria-hidden="true"></i>
      </a>
    </li>
  </ul>
</nav>
{{ currentState }}

angular material tab content c3js chart not showing

I want to show charts in an angular material tab. But the tab initialization seems to be asynchronous and so c3js can’t find the div #detailed-chart and my tab remains empty.

Template

<mat-card class="col-xs-12">
  <mat-card-title>
    Detailed Utilization
  </mat-card-title>

  <mat-tab-group>
    <mat-tab label="Chart">
      <div id="detailed-chart" style="height: 200px"></div>
    </mat-tab>
    <mat-tab label="Table">
    </mat-tab>
  </mat-tab-group>
</mat-card>

Component

export class UtilizationComponent implements OnInit {
  ngOnInit() {       
    this.detailedChart = c3.generate({
      bindto: '#detailed-chart',
      data: {
        x: 'date',
        columns: [
          ['date'],
          ['room'],
          ['desk'],
          ['office']
        ]
      },
      axis: {
        x: {
          type: 'timeseries',
          tick: {
            format: '%m.%Y'
          }
        },
        y: {
          tick: {
            format: d3.format('.1%')
          }
        }
      }
    });   
  }

}

I also tried to find the div manually and it seems not to exist.

const x = window.document.getElementById('detailed-chart');
console.log('foo', x);

Output

foo null

Question

What is the angluarish way to load dynamic elements here? Do I neet to create a separate componant for this tab?

Prevent multiple click event when clicking child element [duplicate]

This question already has an answer here:

I have a list of elements.

Each element have a global click event and a child icon which should also be clickable.

Example :

<div class="parent-element" (click)="clickParent()">
   <span class="button" (click)="childClick()">
   </span>
</div>

For now when I click on the span, both click are fired. How can I separate it from the parent click event ?

How to Instantiate a model class in another model class?

I have one to one relationship in the back-end, and in the Angular, I have two models: Child and ChildPermission both standalone no extension.

I want to instantiate ChildPermission model in the Child model but it is giving an undefined error.

Child class:

import {ChildPermission} from './childpermission';
export interface Child {

  id: number;
  class_id: number;
  f_name: string;
  l_name: string;
  permission: ChildPermission;
}

ChildPermission:

export interface ChildPermission {

  id: number;
  walking: boolean;
  biking: boolean;
  player_water: boolean;
  go_parks: boolean;
  go_fields: boolean;
  using_photos: boolean;
}

In the component I tried the following:

export class ChildAddComponent implements OnInit {

  child: Child = {} as Child;

  constructor() {

  }

  ngOnInit() {
    this.child.permission.walking = true;
    console.log(this.child);
  }

}

But it returns the following in the console:

TypeError: undefined is not an object (evaluating
‘this.child.permission.walking = true’)

Checking if a person is turning a specific age this year with TypeScript (JavaScript)

I think my problem is easy to solve but I just can’t get the hang of it.
I want a function, which checks if the person is turning 18 in the current year, but the person doesn’t have to be already 18 at the moment of checking.

Example:
“Mike turns 18 next week”. So he’s still 17 today, but the function should return true, because he’s turning 18 this year. If Mike turns 18 in the next year, the function should return false.

This is what I got so far, but this function only checks if the person is already 18 or not.

dateString = "2000-02-23" // person is 17 but turns 18 next week, so function should return true
otherDateString = "2001-01-13" //person is also 17, but function should return false, because this person just turnt 17 this year and will turn 18 next year

calculateAge(dateString) {
    let birthday = new Date(dateString);
    let ageDifMs = Date.now() - birthday.getTime();
    let ageDate = new Date(ageDifMs); // milliseconds from epoch
    let age = Math.abs(ageDate.getFullYear() - 1970);
    console.log(age);
    if (age>=18)
      return true;
  }

How do I have to change the function to just check if the person is turning 18 this year, no matter if the person is still 17 yet?

Chrome debugger – parameters in async functions called from template

I my template in angular I use following component:

 <building-selection 
     (done)="sendToBackend($event)"
     >
 </building-selection>

This component show buildings images with checkboxes to user and when he finish checking it emit event with array with chosen buildings

In typescript code below function works:

public async sendToBackend(buildings) 
{
    console.log({buildings}); 
    debugger; // I see buildings "debugger variable preview"
    ... 
}

But if I comment out console.log then in “debugger variable
preview” i see message (if we have non-async function then such phenomenon not appear):

ReferenceError: buildings is not defined at eval (eval at
(http://project.localhost:3003/main.bundle.js:53596:17),
:1:1) at ClientProjectEditorComponent.

… invokeTask
(http://project.localhost:3003/polyfills.bundle.js:14037:14)? at
HTMLUnknownElement.globalZoneAwareCallback
(http://project.localhost:3003/polyfills.bundle.js:14063:17)”
proto
:
Error

Question: Why debugger key word works different when console statement is commented out?

How to align ion-inputs one by one in ion-list

I am new to Ionic framework – (Using Ionic framework 3)

<ion-row>
      <ion-col>
        <ion-list inset>
            <ion-item>
                <ion-input name="products" id="" type="text" required></ion-input><br>
                <ion-input name="products" id="" type="text" required></ion-input><br>
            </ion-item>
        </ion-list>
      </ion-col>
</ion-row>

Above ionic html code generating input fields side by side. But I want input fields one after the other

Please refer attachment that tells about my issue.

Please guide me through the correct way. Thank you. Issue image

How to limit properties in typescript objects to strictly defined properties

Given the following code:

interface t1 {
  prop1: string;
}

interface t2 {
  prop2: string;
}

type ts = t1 | t2;

const t: ts = {
  prop1: 'foo',
  prop2: 'bar'
}

How come the t object is valid? And is that possible to disallow, so t can only be either t1 or t2, but not both at the same time?

Code can be seen on the typescript playground here.

Trouble with MdDialogRef from Angular Material testing angular app

Would anyone help me please!
I’m trying to test my LoginComponent that uses Angular Material, I already use MdDialogRef on production code and this is my test class so far, where I just want to fill all dependencies to make it run:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';

import {
  MdDialogModule,
  MdDialogRef
} from '@angular/material';

import { LoginComponent } from './login.component';
import { AppMaterialModule } from 'app/module/app-material.module';
import { CustomDialogModule } from 'app/module/custom-modal/custom-dialog.module';

fdescribe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LoginComponent],
      imports: [
        ReactiveFormsModule,
        MdDialogModule,
        AppMaterialModule,
        CustomDialogModule
      ],
      providers: [
        MdDialogRef
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

and I keep getting this error: Failed: Can't resolve all parameters for MdDialogRef: (?, ?).

Any helps? Thanks!