gpt4 book ai didi

javascript - 在订阅功能之外无法访问数据

转载 作者:行者123 更新时间:2023-12-03 03:41:57 25 4
gpt4 key购买 nike

我正在加载组件之间传递数据。当组件在订阅函数内接收信息时,它能够使用数据并对其执行任何操作,因此 console.log 工作正常,因此它显然正在接收数据,但在订阅函数之外,信息无法访问,并且未定义。所以我无法运行 console.log 或对这些信息执行任何操作。在html中,它也说它是未定义的。

组件。

import { Observable } from 'rxjs/Rx';
import { User } from '../User';
import { AccountInfo } from './../AccountInfo';
import { LoginService } from './../login.service';
import { Component, OnInit, AfterViewInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/map';

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit, AfterViewInit {

public user: User;
public subscription: Subscription;

constructor(route: ActivatedRoute, private loginService: LoginService) {}

ngOnInit() {
this.loginService.getMessage().subscribe(data =>
{
this.user = data;
console.log(this.user.vendorname);
});

console.log(this.user.vendorname);

}

ngAfterViewInit() {
//Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
//Add 'implements AfterViewInit' to the class.
}

}

html的相关部分

<h1>Welcome {{user.vendorname}}</h1>

最佳答案

是的..这就是async函数的工作原理。您传递给 subscribe 函数的内容是另一个函数。

data => {
this.user = data;
console.log(this.user.vendorname);
}

一旦getMessage()收到来自服务器的应答,就会调用此函数。 subscribe 之后的任何语句都将立即被调用,这就是为什么当您尝试将其记录到此处时 this.user.vendorname 仍然未定义。

如果您在 html 中收到错误,您应该使用安全导航运算符 (?.):

<h1>Welcome {{user?.vendorname}}</h1>

关于javascript - 在订阅功能之外无法访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45572271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com