Answer the question
In order to leave comments, you need to log in
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
{"login": "test", "ban": 0}
...
import { UserService } from './shared/user.service';
...
providers: [ UserService ],
...
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']; // <- В этом моменте непонятности
}
);
}
}
{"login": "test", "ban": 0}
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
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.
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.
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$;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question