将对象从LoginComponent传递到ProfilComponent

问题描述 投票:-1回答:1

我从角度开始,我的问题是如何将对象(connectedUser)从LoginComponent传递到ProfilComponenet

先谢谢您

angular typescript
1个回答
0
投票

尝试这样:

export Class LoginComponent {
myobject = {}

}

在模板中:

<app-profile-component [data]="myobject"></app-profile-component> 

在应用配置文件Component中:

export class ProfileComponent {
@input() data : any; // Object is Recived here 

}

0
投票

这是实现它的几种方法之一。首先,我创建一个服务名称AppStateService(app-state.service.ts)来保存和共享一个对象。希望对您有帮助。

app-state.service.ts文件:

@Injectable({
  providedIn: 'root',
})
export class AppStateService {
  private _connectedUser: any = undefined;

  public get connectedUser(): any {
    return this._connectedUser;
  }
  public set connectedUser(value: any) {
    this._connectedUser = value;
  }
}

login.component.ts文件:

constructor(private appState: AppStateService) { }

public onLoggedin(): void {
  this.authService.login(username, password).subscribe(res => {
    this.appState.connectedUser = res.data;
  });
}

profile.component.ts文件:

public connectedUser;

constructor(private appState: AppStateService) { }

ngOnInit(): void {
  this.connectedUser = this.appState.connectedUser;
  console.log('I:--START--:--ProfileComponent OnLoad--:connectedUser/', connectedUser);
}
© www.soinside.com 2019 - 2024. All rights reserved.