angularjs Angular如何在BehaviorSubject中显示接收到的数据

am46iovg  于 2023-06-21  发布在  Angular
关注(0)|答案(2)|浏览(129)

我尝试使用service从API接收数据,并使用BehaviorSubject将其传递给组件,然后在屏幕上显示它:
这是服务代码:

@Injectable({
    providedIn: 'root',
})
export class UserService {
    userOnChange: BehaviorSubject<User | null> = new BehaviorSubject<User | null>(null);

    constructor(private api: HttpRequestService) {}

    getCurrentUser() {
        this.api.get<User>('/user/me', new HttpParams()).subscribe({
            next: response => {
                this.userOnChange.next(response.body);
            },
        });
    }
}

组件代码:

@Component({
    selector: 'app-topbar',
    templateUrl: './topbar.component.html',
    styleUrls: ['./topbar.component.scss'],
})
export class TopbarComponent implements OnInit {
    public user: User | null = new User();

    constructor(
        private authService: AuthService,
        private router: Router,
        public userService: UserService,
    ) {
                this.userService.userOnChange.subscribe({
            next: value => {
                if (value != null) {
                    this.user = value as User;
                    console.log(value.Username);
                    console.log(this.user.Username);
                }
            },
        });
    }

    ngOnInit(): void {

    }
}

模板代码:

<span *ngIf="this.user && this.user != null"> user: {{ this.user.Username }}</span>

当主题发出新用户时,模板上显示的值不会更改,并且subscribe块中的console.log写入未定义
你能告诉我我哪里做错了吗?

rryofs0p

rryofs0p1#

你需要等待回应。这样的东西应该会有帮助(未测试)

getCurrentUser() {
    this.api.get<User>('/user/me', new HttpParams()).subscribe({
        next: async response => {
            this.userOnChange.next(await response.body);
        },
    });
}

如果这不能得到你需要的,并且你的值实际上是JSON,那么试试.json。

getCurrentUser() {
    this.api.get<User>('/user/me', new HttpParams()).subscribe({
        next: async response => {
            this.userOnChange.next(await response.json());
        },
    });
}
b0zn9rqh

b0zn9rqh2#

我没有看到任何人调用getCurrentUser(),因此实际上没有人触发http请求:

@Component({
    selector: 'app-topbar',
    templateUrl: './topbar.component.html',
    styleUrls: ['./topbar.component.scss'],
})
export class TopbarComponent implements OnInit {
    public user: User | null = new User();

    constructor(
        private authService: AuthService,
        private router: Router,
        public userService: UserService,
    ) {
        this.userService.userOnChange.subscribe({
            next: value => {
                if (value != null) {
                    this.user = value as User;
                    console.log(value.Username);
                    console.log(this.user.Username);
                }
            },
        });
        this.userService.getCurrentUser(); <-- try adding this
    }

    ngOnInit(): void {

    }
}

除此之外,您当前的实现需要处理组件销毁后获得的订阅。你可以通过这种简化来避免它:

export class TopbarComponent implements OnInit {
    public user$: BehaviorSubject<User | null>;

    constructor(
        private authService: AuthService,
        private router: Router,
        private userService: UserService,
    ) {
        this.user$ = this.userService.userOnChange;
        this.userService.getCurrentUser();
                
    }

    ngOnInit(): void {

    }
}

和模板:

<span *ngIf="user$ as user"> user: {{ user.Username }}</span>

相关问题