api 的数据仅在 angular 刷新页面后显示
Data from api is diplayed only after refreshing the pages in angular
我是 angular 的新手,我正在做一个 angular 项目。我面临的一个问题是,在每个组件路由数据之后最初不显示但在重新加载页面后数据显示如下所示
[![重新加载后][2]][2].
和
[2]: https://i.stack.imgur.com/Wn3Bv.png
服务中使用的代码是
import { Injectable, SimpleChange } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
import { environment } from 'src/environments/environment';
import { RouterModule, Routes, ActivatedRoute, Router } from '@angular/router'
@Injectable({ providedIn: 'root' })
export class UserService {
public userList = [];
public userData = [];
public header: any;
public userkeypair: any;
constructor(private http: HttpClient,
private router: Router) {
this.header = new HttpHeaders()
.set("Authorization", 'Bearer ' + JSON.parse(localStorage.getItem('token')));
}
ListAlUsers() {
this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(map(rese => {
return { rese }
}))
.subscribe((result: any) => {
this.userList.push(result);
this.userData = this.userList[0].rese;
var stst: any;
var useraary:any=[];
for (let i = 0; i < this.userData.length; i++) {
if (this.userData[i].status == "True") {
stst = "Active";
} else {
stst = "Inactive";
}
this.userkeypair = {
"id": this.userData[i].id, "name": this.userData[i].fullName, "email": this.userData[i].emailId, "account": this.userData[i].relatedAccount,
"status": stst
}
useraary.push(this.userkeypair);
}
sessionStorage.setItem('userlist',JSON.stringify(useraary));
});
}
}
而 component.ts 是
import { Component, OnInit } from '@angular/core';
import{UserService} from './user.service';
@Component({
selector: 'app-user',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class userComponent {
public Userlst=[];
constructor(private UserService:UserService) {
this.UserService.ListAlUsers();
this.Userlst=JSON.parse(sessionStorage.getItem('userlist'));
}
}
请帮我解决这个问题
James,你的服务应该 return observables,并且你订阅了组件。如果你想用服务中的响应做“某事”,请使用“点击”。例如
注意:map是对response进行变换,不变换就不要用
ListAlUsers() {
//see that you use "return"
return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(tap(rese => {
..make what ever with the response..
..well, the code you has in subscribe...
}
在你的组件中
//see that you equal this.Userlst IN the subscribe function
this.UserService.ListAlUsers().subscribe(_=>{
this.Userlst=JSON.parse(sessionStorage.getItem('userlist'));
}
注意:您将值存储在 SesionStorage 中,如果您不希望该值在会话之间保持不变,那么您真的不需要
Update关于不在SessionStorage中。我们希望服务 return 的数据类似于 useraary
。所以我们使用“map”来转换值
ListAlUsers() :Observable<any>{ //<--I indicate thar return an Observable
//see that you use return this.http.., yes! we return an observable
return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(
.map((result: any) => {
//map can be so complex as we want
this.userList.push(result);
this.userData = this.userList[0].rese;
var stst: any;
const useraary:any=[]; //<--NOT use var, use const or let
for (let i = 0; i < this.userData.length; i++) {
//I use a ternary operator instead an if
const stst=(this.userData[i].status == "True")?"Active":"Inactive"
this.userkeypair = {
"id": this.userData[i].id, "name": this.userData[i].fullName, "email": this.userData[i].emailId, "account": this.userData[i].relatedAccount,
"status": stst
}
useraary.push(this.userkeypair);
}
//and we simply return the value
return useraary;
});
}
在我们的组件中
this.UserService.ListAlUsers().subscribe(response=>{
this.Userlst=response
}
我是 angular 的新手,我正在做一个 angular 项目。我面临的一个问题是,在每个组件路由数据之后最初不显示但在重新加载页面后数据显示如下所示
[![重新加载后][2]][2].
和 [2]: https://i.stack.imgur.com/Wn3Bv.png
服务中使用的代码是
import { Injectable, SimpleChange } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
import { environment } from 'src/environments/environment';
import { RouterModule, Routes, ActivatedRoute, Router } from '@angular/router'
@Injectable({ providedIn: 'root' })
export class UserService {
public userList = [];
public userData = [];
public header: any;
public userkeypair: any;
constructor(private http: HttpClient,
private router: Router) {
this.header = new HttpHeaders()
.set("Authorization", 'Bearer ' + JSON.parse(localStorage.getItem('token')));
}
ListAlUsers() {
this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(map(rese => {
return { rese }
}))
.subscribe((result: any) => {
this.userList.push(result);
this.userData = this.userList[0].rese;
var stst: any;
var useraary:any=[];
for (let i = 0; i < this.userData.length; i++) {
if (this.userData[i].status == "True") {
stst = "Active";
} else {
stst = "Inactive";
}
this.userkeypair = {
"id": this.userData[i].id, "name": this.userData[i].fullName, "email": this.userData[i].emailId, "account": this.userData[i].relatedAccount,
"status": stst
}
useraary.push(this.userkeypair);
}
sessionStorage.setItem('userlist',JSON.stringify(useraary));
});
}
}
而 component.ts 是
import { Component, OnInit } from '@angular/core';
import{UserService} from './user.service';
@Component({
selector: 'app-user',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class userComponent {
public Userlst=[];
constructor(private UserService:UserService) {
this.UserService.ListAlUsers();
this.Userlst=JSON.parse(sessionStorage.getItem('userlist'));
}
}
请帮我解决这个问题
James,你的服务应该 return observables,并且你订阅了组件。如果你想用服务中的响应做“某事”,请使用“点击”。例如
注意:map是对response进行变换,不变换就不要用
ListAlUsers() {
//see that you use "return"
return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(tap(rese => {
..make what ever with the response..
..well, the code you has in subscribe...
}
在你的组件中
//see that you equal this.Userlst IN the subscribe function
this.UserService.ListAlUsers().subscribe(_=>{
this.Userlst=JSON.parse(sessionStorage.getItem('userlist'));
}
注意:您将值存储在 SesionStorage 中,如果您不希望该值在会话之间保持不变,那么您真的不需要
Update关于不在SessionStorage中。我们希望服务 return 的数据类似于 useraary
。所以我们使用“map”来转换值
ListAlUsers() :Observable<any>{ //<--I indicate thar return an Observable
//see that you use return this.http.., yes! we return an observable
return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(
.map((result: any) => {
//map can be so complex as we want
this.userList.push(result);
this.userData = this.userList[0].rese;
var stst: any;
const useraary:any=[]; //<--NOT use var, use const or let
for (let i = 0; i < this.userData.length; i++) {
//I use a ternary operator instead an if
const stst=(this.userData[i].status == "True")?"Active":"Inactive"
this.userkeypair = {
"id": this.userData[i].id, "name": this.userData[i].fullName, "email": this.userData[i].emailId, "account": this.userData[i].relatedAccount,
"status": stst
}
useraary.push(this.userkeypair);
}
//and we simply return the value
return useraary;
});
}
在我们的组件中
this.UserService.ListAlUsers().subscribe(response=>{
this.Userlst=response
}