I'm trying to build a simple application that allows users to submit codes to a database and simply display those codes back to them. My database model looks like this, where the text is the actual code to be displayed. For some reason I cannot get the codes to display on the webpage and it's probably something small. Currently, nothing displays on the webpage, but the API test works in soapUI
Here is my API to get codes
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}`,
});
}
});
my code schema
let codeSchema = new Schema(
{
text: { type: String, unique: true, dropDups: true },
},
{ collection: "codes" }
);
module.exports = mongoose.model("Code", codeSchema);
My home.ts file
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);
}
}
and my HTML
<ng-container matColumnDef="code">
<th mat-header-cell *matHeaderCellDef> Codes </th>
<td mat-cell *matCellDef="let code"> {{codes}} </td>
</ng-container>
CodePudding user response:
Your ts file should also define the displayed columns like this:
displayedColumns: string[] = ['code'];
And your HTML file should be like this:
<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>
The above should work only if your API returns an array of strings e.x.
const codes = ['code1', 'code2', 'code3'];
CodePudding user response:
TRy this:
<td mat-cell *matCellDef="let code"> {{codes | json}} </td>