来自订阅角度 13 的异步模板绑定

发布于 2025-01-18 15:49:13 字数 1662 浏览 4 评论 0原文

我正在尝试在 subscribe上绑定 ngoninit ,以下是页面 profile.component.ts

export class ProfileComponent implements OnInit {
  public userDetailsArr: UserDetails[] = [];
  private subscriptions: Subscription[] = [];

 async ngOnInit() {
    await this.userManagementService.currentUsersIdValue
      .subscribe(async (userId: number) => {
        const user = await this.userManagementService.getUsers(userId.toString())
          .subscribe(x => {
            this.userDetailsArr = x;
            console.log(this.userDetailsArr); // data shows here
          });
        this.subscriptions.push(user);
      });

  console.log(this.userDetailsArr); // data does not show here
}

}

这是html模板页 profile.component.html 如下所示。

<form>
    <div>
      <ng-container *ngIf="userDetailsArr as obj">
        {{ obj.firstName }} //does not show data
      </ng-container>
    </div>
    <input type="text" placeholder="First Name" [(ngModel)]="userDetails.FirstName" /> //does not bind model
</form>

数据以这种格式出现。

[{
  id: 9, addressID: 0, firstName: 'Dang', lastName: 'Kumar'
}]

我成功地在JSON中获得了数据,但是

  1. 它以 camelcase 接收到,但是我的模型是 pascalcase
  2. 它不会在{{obj.firstname}}}}}[(ngmodel)] =“ userDetails.firstname” 因为后者是帕斯卡尔(Pascal),我理解,即将到来的Json是骆驼。
  3. 即使我在subscribe userDetails.firstname =“ test”中传递,它仍然不会在上绑定[(ngmodel)] =“ userdetails.firstname”

I'm trying to bind data on subscribe on ngOninit, here is the page profile.component.ts below.

export class ProfileComponent implements OnInit {
  public userDetailsArr: UserDetails[] = [];
  private subscriptions: Subscription[] = [];

 async ngOnInit() {
    await this.userManagementService.currentUsersIdValue
      .subscribe(async (userId: number) => {
        const user = await this.userManagementService.getUsers(userId.toString())
          .subscribe(x => {
            this.userDetailsArr = x;
            console.log(this.userDetailsArr); // data shows here
          });
        this.subscriptions.push(user);
      });

  console.log(this.userDetailsArr); // data does not show here
}

}

Here is the HTML template page profile.component.html shown below.

<form>
    <div>
      <ng-container *ngIf="userDetailsArr as obj">
        {{ obj.firstName }} //does not show data
      </ng-container>
    </div>
    <input type="text" placeholder="First Name" [(ngModel)]="userDetails.FirstName" /> //does not bind model
</form>

Data comes in this format.

[{
  id: 9, addressID: 0, firstName: 'Dang', lastName: 'Kumar'
}]

I get data in JSON successfully but,

  1. It receives in camelCase but my model is of PascalCase
  2. It does not bind data on {{ obj.firstName }} or [(ngModel)]="userDetails.FirstName" as the latter is of Pascal I understand and incoming JSON is of Camel.
  3. Even though i pass within Subscribe userDetails.FirstName = "test" it still won't bind on [(ngModel)]="userDetails.FirstName".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦一生花开无言 2025-01-25 15:49:13

在我使用的服务页面中。 private currentUserId = new subject();
这是下面使用的代码。

  private currentUserId = new Subject<string>();
  public get currentUsersIdValue() {
    return this.currentUserId;
  }
  public set currentUsersIdValue(value) {
    this.currentUserId = value;
  }

现在问题是 new subject(),我将其更改为 new BehaviourSubject('')< /code>,这工作得很好。在订阅期间,subject 不起作用,只有 BehaviorSubject 可以。

In my service page I was using. private currentUserId = new Subject<string>();
Here is the code which was being used below.

  private currentUserId = new Subject<string>();
  public get currentUsersIdValue() {
    return this.currentUserId;
  }
  public set currentUsersIdValue(value) {
    this.currentUserId = value;
  }

Now the issue was the new Subject<string>() which I changed it to new BehaviorSubject<string>(''), this worked perfectly. During subscribe subject would not work only BehaviorSubject would.

余生共白头 2025-01-25 15:49:13

如果您不使用异步管道,则应将组件标记为dirty。也不使用嵌套订阅,我用switchmap()修复了此问题。

const userSubscription = this.userManagementService.currentUsersIdValue.pipe(
   switchMap((userId) => this.userManagementService.getUsers(userId.toString())),
).subscribe((users) => {
  this.userDetailsArr = users;
  this.changeDetector.markForCheck();
});
this.subscriptions.push(userSubscription);

U should mark component as dirty with changeDetector.markForCheck() if u don't use async pipe. Also dont use nested subscriptions, I fixed this with switchMap()

const userSubscription = this.userManagementService.currentUsersIdValue.pipe(
   switchMap((userId) => this.userManagementService.getUsers(userId.toString())),
).subscribe((users) => {
  this.userDetailsArr = users;
  this.changeDetector.markForCheck();
});
this.subscriptions.push(userSubscription);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文