-1

I have a model named Blog

export interface Blog {
  id: number,
  subject: string
}

I want to make a http request as below :

  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);
    });
  }

result of 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"
}

there are extra property named (description/createAt) if I print the model . I do not want to map (description/createAt) to my model.

NOTE: I do not want to do the following method:

this.http.get("url", options).subscribe((response: Blog) => {
  this.model.id = response.id;
  this.model.subject = response.subject;
});

5 Answers5

3

If you not interested in description and createAt then you could.

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);
});

don't forget to import import { map } from 'rxjs/operators';

Spiderman
  • 330
  • 1
  • 8
  • thanks for your answer , I do not want to add more property to my model , because I do not need them …. –  Dec 19 '19 at 16:07
  • 1
    https://www.w3schools.com/howto/howto_js_remove_property_object.asp or you can `delete` the property – Biiz Dec 19 '19 at 16:29
0

If you not want to assign two properties to model you can do two things

1st method:

this.http.get("url", options).subscribe((response: Blog) => {
      this.model.id = response.id
      this.model.id = response.subject
    });

2nd method:

If you are also handing backend than update your fetch query function and get only those attributes which are needed.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
  • thanks for your answer , as I told in my question I do not want to use the first method... Why this happens ? –  Dec 19 '19 at 16:14
-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();  

-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"
            }
         ]
      }


-2

Try this code [there are several sections]


//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());      

  • Hi, and Welcome to StackOverflow! So, what is your question exactly? Simply pasting a bit of code is not enough. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – Psychotechnopath Dec 19 '19 at 16:48