V
V
Vadimqa2019-12-25 09:08:15
typescript
Vadimqa, 2019-12-25 09:08:15

Angular: how to get data from api and declare variables globally?

Help to get user data from the API, assign it to variables that can be used in any of the
UPD components: I remade the script a little, simplified it. Removed old sketches under the spoiler. Now it works, but within the same component. And it doesn't apply to others. And I wanted the variables {{ user?.login }} to be visible globally, in all templates

previous version

API:
{"login": "test", "ban": 0}
Root app.module.ts:
...
import { UserService } from './shared/user.service';
...
providers: [ UserService ],
...

user.service.ts
This is where the problems begin, my understanding of angular is still at the copy-paste level
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

export class User {
      login: string;
      ban: number;
}

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }

  user: User

  ngOnInit() {
    this.http.get('/server/api/userService').subscribe((data: User) => {
    this.user = data;
     test = this.user['login']; // <- В этом моменте непонятности
    }
    );
  }
}

Help at least to start writing the user's login to the console

API
{"login": "test", "ban": 0}
app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';


export class User {
  login: string;
  ban: number;
}


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})


export class AppComponent {

  user: User

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('/server/api/userService').subscribe((data: User) => (this.user = data))
  }

}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2019-12-25
@Seasle

If I'm not mistaken, an instance of the service is created 1, and then all components refer to it. So, you can try to declare a certain storage in the service class, in which you will add data.

S
Sashqa, 2019-12-25
@Sashqa

You create a service, write methods for working with api in this service. You
received data, to transfer it to other components, you can use either a common service, or pass through Input / Output decorators, or even write to localStorage and pull from there.

A
Anton Shvets, 2019-12-25
@Xuxicheta

the simplest service to ask the backend once, cache it and then give it to the components so that they subscribe.

@Injectable({
  providedIn: 'root'
})
class UserService {
  private user$;
  
  constructor(private http: HttpClient) {}

  fetchUser(): Observable<User> {
    if (!this.user$) {
      this.user$ = this.http.get('/server/api/userService').pipe(shareReplay(1))
   }
   return this.user$;
 }
}

It does not need to be loaded anywhere, just placed in the component constructor, where it will be used. Suitable for data that is current and unchanged throughout the life of the application.
And this code won't do you any good if you don't understand what it does.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question