【问题标题】:Angular unable to print JSON data in HTML?Angular 无法在 HTML 中打印 JSON 数据?
【发布时间】:2020-01-30 14:13:29
【问题描述】:

我想从 API 获取数据并在 HTML 页面上打印相同的数据。

我有如下代码。我能够从 API 获取数据并控制台记录 API 数据。但我无法在 HTML 页面上打印相同的内容。

在编译或执行代码时没有显示错误,我认为代码缺少一些东西。到目前为止我看不到任何错误,请帮我解决这个问题 下面给出了component.ts、HTML、Service.ts

component.ts

export class LoginComponent implements OnInit {

    username = '';
    password = '';
    a = '';
    data1 = [];

    constructor(private abc: LoginService, private router: Router) {}

    ngOnInit() {}

    login() {
        console.log(JSON.stringify({
            username: this.username,
            password: this.password
        }));
        this.a = JSON.stringify({
            username: this.username,
            password: this.password
        });
        this.abc.getValues(this.a).subscribe((data: any) => {
            this.data1 = data;
            console.log(data);
            console.log(this.data1);
        });
    }

}

component.html

<div class="wrapper fadeInDown">
    <div id="formContent">
        <!-- Tabs Titles -->
        <!-- Icon -->
        <div class="fadeIn first">
            <h1>Touchworld Technologies</h1>
        </div>
        <!-- Login Form -->
        <form #formData="ngForm">
            <input type="text" id="login" class="fadeIn second" placeholder="username" name="username"
                [(ngModel)]="username">
            <input type="text" id="password" class="fadeIn third" name="password" placeholder="password"
                [(ngModel)]="password">
            <input type="submit" class="fadeIn fourth" value="Log In" (click)="login()">
            <!-- <button class="fadeIn fourth" [routerLink]="['../secondpage']">Home</button> -->
        </form>
        {{data1}}
        <!-- Remind Passowrd -->
        <div id="formFooter">
            <a class="underlineHover" href="#">Go to the Site</a>
        </div>
    </div>
</div>

<ul>
    <li *ngFor="let datas of data1">
        <span>{{datas.id}}</span>
        <span>{{datas.title}}</span>
        <span>Test</span>
    </li>
</ul>

service.ts

export class LoginService {

    constructor(private http: HttpClient) {}

    getValues(a: any) {
        console.log("you have entered");
        console.log(a);
        return this.http.get('https://jsonplaceholder.typicode.com/posts');
    }

}

【问题讨论】:

  • 您可以使用JsonPipe 打印 JSON。话虽如此,正如答案所描述的那样,您正在尝试渲染一个可能尚未声明或定义的变量。
  • 我也试过 JsonPipe,还是不行

标签: angular


【解决方案1】:

您可以在 HTML 端打印 data1,如下在 component.html 中:

{{data1 | json}}

你可以查看参考here

【讨论】:

  • 请确保在 app.module.ts 中导入 CommonModule
  • 导入了 CommonModule,我可以通过控制台记录 api 数据
猜你喜欢
  • 2018-07-13
  • 2020-05-27
  • 1970-01-01
  • 2016-09-16
  • 2014-05-17
  • 2018-07-11
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
相关资源
最近更新 更多