首页 > 解决方案 > Angular 无法在 HTML 中打印 JSON 数据?

问题描述

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

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

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

组件.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);
        });
    }

}

组件.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>

服务.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');
    }

}

标签: angular

解决方案


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

{{data1 | json}}

你可以在这里查看参考


推荐阅读