我有一个名为Blog的模型
export interface Blog {
id: number,
subject: string
}
我要发出一个http请求,如下所示:
public model: Blog = { id: null, subject: "" };
constructor(private http: HttpClient) { }
ngOnInit(): void {
const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
let options = { headers: headers };
this.http.get("url", options).subscribe((response: Blog) => {
this.model = response as Blog;
console.log(this.model);
});
}
console.log(this.model)
{
id: 7
subject: " Claire’s ideal Carer"
description: "I’d like to introduce you to Claire."
createAt: "0001-01-01T00:00:00"
}
如果我打印模型,还有一个名为(description/createAt
)的额外属性。我不想将(description / createAt)映射到我的模型。
注意::我不想执行以下方法:
this.http.get("url", options).subscribe((response: Blog) => {
this.model.id = response.id;
this.model.subject = response.subject;
});
答案 0 :(得分:1)
如果您对description
和createAt
不感兴趣,那么可以。
this.http.get("url", options).pipe(map(data => {
delete data['description'];
delete data['createdAt'];
return data;
}))
.subscribe((response: Blog) => {
this.model = response;
console.log(this.model);
});
别忘了导入import { map } from 'rxjs/operators';
答案 1 :(得分:0)
如果您不想为模型分配两个属性,则可以做两件事
第一种方法:
this.http.get("url", options).subscribe((response: Blog) => {
this.model.id = response.id
this.model.id = response.subject
});
第二个方法:
如果您还提供后端服务,而不是更新获取查询功能并仅获取所需的那些属性。
答案 2 :(得分:-1)
///TODO8 Category.component.ts
this.router.navigate(['/', 'productlist']);
///TODO9 Category-list.component.ts
data => this.categories = data,
err => this.logError(err)
///TODO10 Category-list.component.ts
this.errorService.handleError(error);
///TODO11 Category.service.ts
return this.http.get(this.categoryUrl)
.map((res: Response) => this.extractCategory(res))
.catch(this.handIeError);
///TODO12 CanActivateGuard.ts
window.confirm('There is no item in basket. Please add item(s) in basket!');
return false;
///TODO13 LogedInAuthGuard.ts
return this.authService.isLoggedIn();
///TODO14 product.filter.ts
return items.filter(item => item.name.toLowerCase().index0f(args.toLowerCase()) !== -1);
///TODO15 product-list.component.ts
this._productService.getProduct().subscribe(
data =>this.setProducts(data),
err =>this.logError(err)
///TODO16 product-list.component.ts
if(this.currentProductType === 'fruits')
{
return this.fruits;
}
else if(this.currentProductType === 'vegetables')
{
return this.vegetables;
}
else if(this.currentProductType === 'grocery')
{
return this.grocery;
}
///TODO17 product-list.component.ts
let canNavigate =this._productService.getMyBasket() &&
this._productService.getMyBasket().length >0;
this.router.navigate(['/', 'basket', {data: canNavigate}] );
///TODO18 product-list.component.ts
this._productService.addProductToBasket(product)
this.tota Iltems = this._productService.getTotalBasketQuantity();
///TODO19 product.services.ts
if(!this.myBasket)
{
this.myBasket = [];
}
var index = this.myBasket.indexOf(product);
if(index!== -1){
this.myBasket[index].basketCount++;
}
else{
if(!product.basketCount){
product.basketCount = 0;
}
product.basketCount++;
this.myBasket.push(product);
}
this.setTotalProductBasketPrice(product);
///TODO20 product.services.ts
var tCount:number = O;
if(this.myBasket){
this.myBasket.forEach(function(product: Product){
tCount = tCount + product.basketCount;
})
}
return tCount;
///TODO21 product.services.ts
if(this.myBasket){
this.myBasket.forEach(function(product: Product){
product.basketCount = O;
product.basketPrice = 0;
})
}
this.myBasket = null;
///TODO22 product.services.ts
var tPrice:number = O;
if(this.myBasket){
this.myBasket.forEach(function(product: Product){
tPrice = tPrice + product.basketPrice;
})
}
return tPrice;
///TODO23 product.services.ts
return this.http.get(this.productsUrl)
.map((res: Response) => this.extractProduct(res))
.catch(this.handleError);
///TODO24 product.services.ts
let errMsg = (error.message) ? error.message :
error.status ? ‘${error.status} - ${error.statusText}‘ : 'Server error';
return Observable.throw(errMsg);
///TODO25 product.service.ts
return this.myBasket;
///TODO26 basket.component.ts
this.myBasket = this._productService.getMyBasket();
///TODO27 basket.component.ts
this.quantity = this._productService.getTotaIBasketQuantity();
this.totalPrice = this._productService.getTotalPrice();
///TODO28 my-basket.component.ts
this.router.navigate(['/', 'checkout']);
///TODO29 checkout.component.ts
this.paymentMessage = this.authService.isLoggedln() ? 'You can place your order ' + items : 'Before you place your order > Signln';
///TODO30 basket.component.ts
this.router.navigate(['/', 'home']);
///TODO31 basket.component.ts
this._productService.resetBasket();
答案 3 :(得分:-1)
// TODON1 models/user.js
var schema = new Schema({
userName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true}
});
///TODON2 models/user.js
module.exports = mongoose.model('User', schema);
///TODON03 router/user.js
var user = new User({
userName: req.body.userName,
password: bcrypt.hashSync(req.body.password, 10),
email: req.body.email
});
user.save(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(201).json({
message: 'User created',
obj: result
});
});
///TODON04 router/user.js
User.findOne({email: req.body.email}, function(err, user) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!user) {
return res.status(401).json({
title: 'Login failed',
error: {message: 'Invalid login credentials'}
});
}
if (!bcrypt.compareSync(req.body.password, user.password)) {
return res.status(401).json({
title: 'Login failed',
error: {message: 'Invalid login credentials'}
});
}
var token = jwt.sign({user: user}, 'secret', {expiresIn: 7200});
res.status(200).json({
message: 'Successfully logged in',
token: token,
userId: user._id
});
});
///TODON5 app.js
var mongoose = require('mongoose');
///TODON6 app.js
mongoose.connect('localhost:27017/ebasket');
///TODON7 app.js
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
///TODON8 app.js
var express = require('express');
var cookieParser = require('cookie-parser');
///TODON9 app.js
app.use(cookieParser());
///TODON10 app.js
var app = express();
///TODON11 router/user.js
var router = express.Router();
///TODON12 public/data/category.json
{
"type": "Fruits",
"id": "fruits",
"products": [
{
"label": "Fresh Fruits",
"id": "freshFruits"
},
{
"label": "Herbs",
"id": "herbs"
},
{
"label": "Fresh Vegetable",
"id": "freshVegetable"
}
]
},
{
"type": "Vegetables",
"id": "vegetables",
"products": [
{
"label": "Fresh Vegetables",
"id": "fresh"
},
{
"label": "Frozen Vegetables",
"id": "frozen"
},
{
"label": "Cut Vegetables",
"id": "cutvege"
}
]
},
{
"type": "Groceries",
"id": "grocery",
"products": [
{
"label": "Detergents",
"id": "detergent"
},
{
"label": "Toilet/Floor cleaner",
"id": "herbs"
},
{
"label": "Breakfast Cereals",
"id": "cereals"
}
]
}
答案 4 :(得分:-2)
尝试此代码[有几个部分]
//TODO1
userName: new FormControl(null, [Validators.required, Validators.maxLength(20),
Validators.minLength(8)]),
email: new FormControl(null, [
Validators.required,
Validators.pattern(" [a-zO-9 !#$%&‘*+/=?"_‘{ | }~-]+(?:\.[a-zO-9!#$%&'*+/=?"_‘{ | }"’-
]+)*@(?:[a—zO-9](?:[a-zO-9—]*[a-zO-9])?\.)+[a-zO—9](?z[a-zO-9-]*[a-zO-9])?")
1),
password: new FormControl(null, [Validators.required, Validators.minLength(6)])
//TODO2
data => {
this.router.navigate(['/', 'signin']);
//TODO3
.map((response: Response) => response.json())
.catch((error: Response) =>{
this.errorService.handleError(error.json());
return Observable.throw(error.json());
});
//TODO4
this.router.navigate(['/', 'signin']);
//TODO5
email: new FormContro|(null,[
Validators.required,
Validators.pattern(" [a-zO-9 !#$%&'*+/=?"_‘{| }~-]+(?:\.[a-zO-9!#$%&'*+/=?"_‘{ | }"’—
]+)*@(?:[a-zO—9](?:[a-zO-9-]*[a-zO-9])?\.)+[a-zO-9](?:[a-zO—9-]*[a-zO-9])?")
1),
password: new FormControl(null, Validators.required)
//TODO6
data =>{
IocaIStorage.setltem('token', data.token);
IocaIStorage.set|tem('userld', data.user|d);
this.router.navigate(['/', 'home']);
},
error => console.error(error)
//TODO1
userName: new FormControl(null, [Validators.required, Validators.maxLength(20),
Validators.minLength(8)]),
email: new FormControl(null, [
Validators.required,
Validators.pattern(" [a-zO-9 !#$%&‘*+/=?"_‘{ | }~-]+(?:\.[a-zO-9!#$%&'*+/=?"_‘{ | }"’-
]+)*@(?:[a—zO-9](?:[a-zO-9—]*[a-zO-9])?\.)+[a-zO—9](?z[a-zO-9-]*[a-zO-9])?")
1),
password: new FormControl(null, [Validators.required, Validators.minLength(6)])
//TODO2
data => {
this.router.navigate(['/', 'signin']);
//TODO3
.map((response: Response) => response.json())
.catch((error: Response) =>{
this.errorService.handleError(error.json());
return Observable.throw(error.json());
});
//TODO4
this.router.navigate(['/', 'signin']);
//TODO5
email: new FormContro|(null,[
Validators.required,
Validators.pattern(" [a-zO-9 !#$%&'*+/=?"_‘{| }~-]+(?:\.[a-zO-9!#$%&'*+/=?"_‘{ | }"’—
]+)*@(?:[a-zO—9](?:[a-zO-9-]*[a-zO-9])?\.)+[a-zO-9](?:[a-zO—9-]*[a-zO-9])?")
1),
password: new FormControl(null, Validators.required)
//TODO6
data =>{
IocaIStorage.setltem('token', data.token);
IocaIStorage.set|tem('userld', data.user|d);
this.router.navigate(['/', 'home']);
},
error => console.error(error)
//TODO7
.map((response: Response) => response.json())
.catch((error: Response) =>{
this.errorService.handleError(error.json());
return Observable.throw(error.json());
//TODO7
.map((response: Response) => response.json())
.catch((error: Response) =>{
this.errorService.handleError(error.json());
return Observable.throw(error.json());