0

当我在我的 html{{user.firstName}}中使用它时,数据显示但有错误,但是当我在我的 html{{user?.firstName}}中使用它时,数据没有显示但没有错误,但是当我单击按钮时,数据正在显示。大家好,我正在使用 metronic 和 angular8

你有关于如何显示数据的替代人吗?

import { Component, OnInit, enableProdMode } from "@angular/core";
import { DealerapiService } from "../services/dealerapi.service";
import { DomSanitizer } from "@angular/platform-browser";
import { FormGroup, FormBuilder } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";

@Component({
    selector: "kt-home-profile",
    templateUrl: "./home-profile.component.html",
    styleUrls: ["./home-profile.component.scss"]
})
export class HomeProfileComponent implements OnInit {
    constructor(
        private dealerApiService: DealerapiService,
        private domSanitizer: DomSanitizer,
        private formBuilder: FormBuilder,
        private route: ActivatedRoute
    ) {}
    forms: any;
    profileForm: FormGroup;
    imageurl: any;
    username: any;
    user: any;
    ngOnInit() {
        this.route.params.subscribe(params => {
            // get the username out of the route params
            this.username = params["username"];

            const username = params["username"];
            this.dealerApiService
                .getUserbyUsernameProfile(username)
                .subscribe((user: any) => {
                    this.user = user.data;
                    console.log(user);
                });
        });

    }

}
4

3 回答 3

4

这正是我的问题.... Metronic 主题没有将接收到的数据从 API 呈现到模板。它在发出事件后呈现接收到的数据。因此,您可以将单击功能绑定到任何已呈现的按钮。

Document.getElementById('alreadyRenderedBTN').click();

...或者只是将ChangeDetectionStrategy.OnPush
更改 为 ChangeDetectionStrategy.Default

app.component.ts里面

于 2020-01-13T05:34:06.440 回答
1

尝试如下,

export class HomeProfileComponent implements OnInit {
  ...
  ...
  user: any; // comment this line
  user = <User>{}; // Add this line

  ...
  ...
}

// Add the below model after your component class
export class User {
  firstName: string;
  lastName: string;
  // remaining properties
}

现在在您的 html 中,您可以在没有 ? 的情况下访问用户属性 (安全操作员)

{{user.firstName}}
于 2020-01-08T06:49:05.100 回答
1

您应该在组件文件本身中分配用户的名字值。试试这个:

firstName: string;
// other variables

// ..other code..

this.dealerApiService
  .getUserbyUsernameProfile(username)
     .subscribe((user: any) => {
        this.user = user.data;
        // added code
        this.firstname = user['data']['firstName'];
        console.log(user);
      });
   });

现在尝试从您的模板中访问 firstName。

于 2020-01-08T08:29:45.153 回答