0

I am using Components and service Component :

servers:{Name : string , Id:number }[]=[];

ngOnInit() {
    this.Id =   this.route.snapshot.params['id'];
}

Service :

server_detail=[{Name : 'production',Id    : 1},
               {Name :'Attendance', Id    : 2}];

I am getting Id from the route and want to fetch server name corresponding to that server Id.

4
  • 1
    Please format your code as a code block Commented Aug 21, 2017 at 12:43
  • You want to find name that is correspoding to id given from server? Commented Aug 21, 2017 at 12:45
  • @Oisin formatted for him :D Commented Aug 21, 2017 at 12:49
  • 1
    Yes sir.. i want name of server corresponding to id Commented Aug 21, 2017 at 12:50

1 Answer 1

12

You can find the specific value using the find() method:

// by Id
let server = this.servers.find(x => x.Id === 1);
// or by Name
let server = this.servers.find(x => x.Name === 'production');

UPDATE according to your comment:

ngOnInit() {
    this.servers = this.alldata.server_detail;
    this.server_Id=  this.route.snapshot.params['id'];

    let server = this.servers.find(x => x.Id === this.server_Id);
    if(server !== undefined) {
        // You can access Id or Name of the found server object.
        concole.log(server.Name);
    }
}

If an object is not found, then the find() method will return undefined.

Sign up to request clarification or add additional context in comments.

6 Comments

ngOnInit() { this.servers=this.alldata.server_detail; this.server_Id= this.route.snapshot.params['id']; let server = this.servers.find(x => x.Id === this.server_Id); console.log(this.server_Id);} console.log(server);} server is "undefined" , but server_id having value and servers also have data then why server is undefined @Faisal
@user8331237 are you sure you get all servers data correctly? try to console.log(this.alldata.server_detail) and see if it contains data.
yess.. I checked it out. console.log(this.alldata.server_detail) it contains the data
Share your code on some plunker or in the question.
problem has been solved ... Can you tell me difference between the working of find and filter method
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.