0
使用MEAN(MongoDB Express Angular Node)將下拉的角度爲2的下拉與後端的MonogDB值綁定。Mean Stack:無法使用Angular 2和Node JS綁定下拉菜單
我在節點JS路線和車型如下:
無功\ WWW \ HTML \快\ nodeauthapp主\路徑\ categories.js
//Get all categories
router.get('/get',(req,res,next) => {
//res.send('Get categories');
Categories.getAllCategories((err,categories)=>{
if(err)
{
res.json({success: false, msg:'Failed to get categories'});
}
else
{
res.json({success: true, mainCategories:categories});
}
});
})
\ VAR \ WWW \ HTML \快\ nodeauthapp主\型號\ categories.js
// Categories Schema
const CategoriesSchema = mongoose.Schema({
category_name: {
type: String,
required: true
}
});
const Categories = module.exports = mongoose.model('Categories', CategoriesSchema);
//Get all categories
module.exports.getAllCategories = function(callback){
Categories.find({},callback)
}
- 在角度2 IM結合降倒升邁克:
空白page.component.html
<form role="form">
<fieldset class="form-group">
<label>Select Category</label><br/><br/>
<select [(ngModel)]="selectedObject" name="selectedObject" class="form-control">
<option disabled>--Select--</option>
<option *ngFor="let category of categories" [value]="category">{{category}}</option>
</select>
</fieldset>
</form>
空白page.component.ts
export class BlankPageComponent implements OnInit {
category:String;
public categories: Array<any> = [];
constructor(private addproductService: AddproductService,
private flashMessage: FlashMessagesService,
private router: Router) { }
ngOnInit() {
const category = {
categories: this.category
}
console.log(category);
this.addproductService.loadData(category).subscribe(data => {
if(data.success){
this.categories = data.mainCategories;
console.log('Drop down binded');
} else {
console.log('Not binded');
}
});
}
addproduct.service.ts
export class AddproductService {
category: any;
loadData(category) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('http://10.*.*.*:3000/categories/get', { headers: headers })
.map(res => res.json());
}
}
我從控制檯日誌中獲取下拉菜單,但在前端,似乎沒有綁定值。
當我在postman中打開GET API url時,我得到了類別列表。
在瀏覽器日誌中我得到:對象{類:未定義}
你在哪裏分配響應類別變量? –
這就是我所做的一切,可以請您提出我錯過了什麼! – phyme
您需要定義一個數組公共類別:Array = [];然後在if(data.success){write this.categories = data.mainCategories;試試這個,讓我知道它是否有效。 –