0

i have this function in my service, the articleId and Type are optionnal because not every article have one but it's never reach the else section and the type is assign to the articleId so i get an error Code: 400

  getArticles(name: string, articleId?: string, Type?:Code) {
  if(name && articleId) {
    return this.http.get(environment.api + '?name=' + name + '&articleId=' + articleId);
  }
  else{
    return this.http.get(environment.api + '?name=' + name + '&Type=' + Type);
  }
  
}

did someone can help to fix this error please

Igor
  • 60,821
  • 10
  • 100
  • 175
  • Can you elaborate a bit, not every article have one, what? Do you mean every article doesn't have an article ID or type or both? – Wahab Shah Jul 06 '20 at 19:25
  • yes some article could not have articleId so i have to check his type instead – Mélanie N'hammoucha Jul 06 '20 at 19:29
  • Does this answer your question? [How to pass optional parameters while omitting some other optional parameters?](https://stackoverflow.com/questions/30734509/how-to-pass-optional-parameters-while-omitting-some-other-optional-parameters) – Igor Jul 06 '20 at 19:32
  • I removed angularjs as a tag and added javascript and typescript as the question is more about how to pass in parameters to a method and not how does angular process these parameters in a specific method call. – Igor Jul 06 '20 at 19:34
  • 1
    Something that is of interest though is that you can pass an object to `http.get` that will then be converted and added to the query string. See the [config.params](https://docs.angularjs.org/api/ng/service/$http#usage) argument. Doing this also ensures that the query string values are properly escaped. – Igor Jul 06 '20 at 19:37
  • i dont understand how i could pass 3 parameters if some article dont have articleId? i need to use optional parameter... – Mélanie N'hammoucha Jul 06 '20 at 19:38
  • You would pass `undefined` or `null` or something else that would be evaluated as falsy. Example: `myService.getArticles(nameVar, undefined, typeVar).then(() => ...)` – Igor Jul 06 '20 at 19:38
  • where? in my "if" section? – Mélanie N'hammoucha Jul 06 '20 at 19:40
  • 1
    In the code you did not supply, the code that makes the call to `getArticles` – Igor Jul 06 '20 at 19:41

1 Answers1

0

You can check for articleId != "" and run the if condition and otherwise else condition would run. So Like lets say your articelId is there so It will go inside if and execute, no need to check for name because its already there for both article and type. And if your articleId is null then else condition will run with type passed.

Wahab Shah
  • 2,066
  • 1
  • 14
  • 19