我正在嘗試構建一個簡單的應用程式,它允許用戶將代碼提交到資料庫并簡單地將這些代碼顯示給他們。我的資料庫模型如下所示,其中文本是要顯示的實際代碼。出于某種原因,我無法讓代碼顯示在網頁上,它可能很小。目前,網頁上沒有顯示任何內容,但 API 測驗在soapUI 中有效
這是我獲取代碼的 API
router.get("/codes", async(req, res) => {
try {
Code.find({}, function(err, codes) {
if (err) {
console.log(err);
res.status(501).send({
message: `MongoDB Exception: ${err}`,
});
} else {
console.log(codes);
res.json(codes);
}
});
} catch (e) {
console.log(e);
res.status(500).send({
message: `Server Exception: ${e.message}`,
});
}
});
我的代碼架構
let codeSchema = new Schema(
{
text: { type: String, unique: true, dropDups: true },
},
{ collection: "codes" }
);
module.exports = mongoose.model("Code", codeSchema);
我的 home.ts 檔案
export class HomeComponent implements OnInit {
codes = new MatTableDataSource<Code>([]);
constructor(private http: HttpClient) {}
fetchCodes(): void {
this.http
.get('http://localhost:3000/api/codes')
.subscribe((res: Code[]) => {
this.codes.data = res;
});
}
ngOnInit(): void {
this.fetchCodes();
console.log(this.codes);
}
}
和我的 HTML
<ng-container matColumnDef="code">
<th mat-header-cell *matHeaderCellDef> Codes </th>
<td mat-cell *matCellDef="let code"> {{codes}} </td>
</ng-container>
uj5u.com熱心網友回復:
您的 ts 檔案還應定義顯示的列,如下所示:
displayedColumns: string[] = ['code'];
你的 HTML 檔案應該是這樣的:
<table mat-table [dataSource]="codes" class="mat-elevation-z8">
<ng-container matColumnDef="code">
<th mat-header-cell *matHeaderCellDef>Code</th>
<td mat-cell *matCellDef="let code"> {{code}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
僅當您的 API 回傳一個字串陣列 ex 時,上述內容才有效
const codes = ['code1', 'code2', 'code3'];
uj5u.com熱心網友回復:
嘗試這個:
<td mat-cell *matCellDef="let code"> {{codes | json}} </td>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/377700.html
標籤:javascript 有角的 打字稿 休息 平均堆栈
