如何使用角度为6的Restcall?

时间:2018-10-26 08:17:02

标签: rest angular6

我对Angular 6完全陌生。

我有一个RestCall,我想在Angular 6中可视化。

  

http://localhost:52126/api/Sudoku/GetDefaultSolution

邮递员返回以下(正确的)答案:

  

“ [{\\ SudokuBoardId \”:0,\“ clusters \”:[{\“ ClusterId \”:0,\“ list \”:[\“ 0,0 \”,\“ 1,0 \“,\” 0,1 \“,\” 1,1 \“]},{\” ClusterId \“:0,\” list \“:[\” 2,0 \“,\” 3,0 \“,\” 2,1 \“,\” 3,1 \“]},{\” ClusterId \“:0,\” list \“:[\” 0,2 \“,\” 1,2 \“,\” 0,3 \“,\” 1,3 \“]},{\” ClusterId \“:0,\” list \“:[\” 2,2 \“,\” 3,2 \“,\” 2,3 \“,\” 3,3 \“]}],\” boardValues \“:[[1,3,2,4],[4,2,3,1],[ 2,1,4,3],[3,4,1,2]],\“ xDimension \”:4,\“ yDimension \”:4}]“”

现在,我想在Angular应用程序中展示它。 html站点显示正确,但其余输出未显示。 这是我的代码:

sudokudata.component.ts:

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'sudokudata',
    templateUrl: './sudokudata.component.html'
})
export class SudokuDataComponent {
    public sudoku: Sudokus;

    constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
        http.get('http://localhost:52126/api/Sudoku/GetDefaultSolution').subscribe(result => {
            this.sudoku = result.json() as Sudokus;
        }, error => console.error(error));
    }
}

interface Sudokus {
    json:string;
}

sudokudata.component.html:

<h1>Sudoku showoff</h1>

<p>This component show one single Sudoku and its solution</p>

<p *ngIf="!sudoku"><em>Loading...</em></p>

<p>{{sudoku.json}}</p>

<table class='table' *ngIf="sudokus">
<thead>
    <tr>
        <th>JSON</th>
    </tr>
</thead>
<tbody>
        <tr>
            <td>{{ sudoku.json }}</td>
        </tr>
    </tbody>
</table>

显示的所有内容是:

  

数独炫耀

     

此组件显示一个数独及其解决方案

     

正在加载...

那么“数独”根本就没有填充?我如何在Json.output中使用该变量?

2 个答案:

答案 0 :(得分:0)

我不确定

this.sudoku = result.json() as Sudokus;

但是我正在使用这样的响应及其工作方式

http.get('http://localhost:52126/api/Sudoku/GetDefaultSolution')
    .subscribe((result: Sudokus) => {
        this.sudoku = result;
    }, error => console.error(error));

答案 1 :(得分:0)

在Angular 6中,您无需调用.json(),因为默认情况下,响应将被解析为JSON并由Angular转换为Javascript对象。

因此,只需将result.json()替换为result

您也不需要as Sudokus,可以让Angular知道返回的响应的类型应该是什么,如下所示:

首先更新您的接口以匹配API返回的任何内容,例如

interface Sudokus { 
 [prop: string]: any;
}

然后在进行API调用时使用Sudokus类型,如下所示:

http.get<Sudokus[]>('http://localhost:52126/api/Sudoku/GetDefaultSolution').subscribe(result => {
            this.sudoku = result;
        }, error => console.error(error));

注意get方法上的<>括号。