E
E
Eugene2018-08-23 13:54:59
Angular
Eugene, 2018-08-23 13:54:59

What is the correct way to instantiate a class in AngularTS?

Good afternoon.
Started to understand with Angular and got stuck on the element operation.
I have a model describing a user:

export class User {
  id?: string;
  name?: string;
  linktoimage?: string;
}

There is a service that processes this model:
import { User } from '../models/User.model';
import { Injectable} from '@angular/core';
import * as signalR from "@aspnet/signalr";
import { Router } from '@angular/router';

@Injectable()
export class UserAuthService {
  url = "http://localhost:52015/auth";
  user: User = new User();
  private connection = new signalR.HubConnectionBuilder().withUrl(this.url, { accessTokenFactory: () => getToken() }).build();
  constructor(private router: Router) {
    this.connection.start().catch(err => { });
    this.connection.on("updateinfo", (state: boolean, ndata: string) => {
      if (state == true) {
        let jsonData = JSON.parse(ndata);
        this.user.name = jsonData.UserName;
        this.user.linktoimage = jsonData.ImageLink;
        this.router.navigate(['/dashboard']);
      }
    });
    this.connection.on("GetToken", (token: string) => {
      this.user.id = token;
      sessionStorage.setItem("token", token);
    });
  }
}

I add the service itself to providers app.browser.module.ts and to the required component:
import { Component } from '@angular/core';
import { UserAuthService } from '../../services/auth.service';
@Component({
  selector: 'welcome',
  template: `<div><button type="button" class="btn btn-block " (click)="StartAuth()"></button></div>`,
  styles: [`:host{ 
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}`],
  providers: [UserAuthService]
})

export class Welcome {
  
  constructor(private _userauth: UserAuthService) { }
  public StartAuth(): void {
    var authwindow = window.open("/api/Auth/Authorization?code=123&scope=" + this._userauth.user.id);

  }
}

The problem is that an instance of the user class and the User class itself for some reason are always always undefined.
Most likely the solution is an elementary one.
By design, an instance of the user class should have only one access for the necessary components.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question