0

I want to concatenate two string in angular 7.

the function is:

getEmployment(id: number): Observable<Employment> {
    const url = '${this.EmploymentUrl}/${id}';
    return this.http.get<Employment>(url).pipe(
      tap(_ => this.log('fetched employment id=${id}')),
      catchError(this.handleError<Employment>('getEmployment id=${id}'))
    );
  }

However, when I inspect element in my web browser it shows that {id} is not found.

If I replace the second line with the following it works just fine.

const url = this.EmploymentUrl + '/' + id;

After a lot of googling I can't figure out why the first method doesn't work. Why doesn't it work and what is the difference between the two methods?

KHans
  • 89
  • 2
  • 8
  • are you using backticks ? From the code it seems like you are using quote. – gunjit May 22 '19 at 12:47
  • 1
    Possible duplicate of [What does ${} (dollar sign and curly braces) mean in a string in Javascript?](https://stackoverflow.com/questions/35835362/what-does-dollar-sign-and-curly-braces-mean-in-a-string-in-javascript) – Prashant Pimpale May 22 '19 at 12:48
  • For template literals to work (`${id}`), you need to use backticks (`\``) instead of single quotes (`'`) – ShamPooSham May 22 '19 at 12:49
  • @gunjit oh wow that solved it. Thank you – KHans May 22 '19 at 12:50

4 Answers4

0

You should use `` instead of quotes. more info here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

getEmployment(id: number): Observable<Employment> {
        const url = `${this.EmploymentUrl}/${id}`;
        return this.http.get<Employment>(url).pipe(
          tap(_ => this.log(`fetched employment id=${id}`)),
          catchError(this.handleError<Employment>(`getEmployment id=${id}`))
        );
      }
sachin kalekar
  • 526
  • 2
  • 9
0

Beacuase you are using quote (') instead backtick (`)

getEmployment(id: number): Observable<Employment> {
    const url = `${this.EmploymentUrl}/${id}`;
    return this.http.get<Employment>(url).pipe(
      tap(_ => this.log('fetched employment id=${id}')),
      catchError(this.handleError<Employment>('getEmployment id=${id}'))
    );
  }
Shifenis
  • 1,056
  • 11
  • 22
0

The answer was simply that I have to use backpacks (`) instead of single quotes (')

Like so:

 const url = `${this.EmploymentUrl}/${id}`;
KHans
  • 89
  • 2
  • 8
0

Or you can just do a simple string concat like

const url:string = this.Employment+'/'+id; // id will be converted into a string
Richie50
  • 71
  • 1
  • 7