Although not used much in modern Japanese, the
suffix 掛(が)け 'support', or 'hanger' followed by に may occasionally appear after the ます-stem of verbs. When seen used this way,
掛(が)けに simply means 'on the way', 'as you go', or 'while doing (A)'. (B) may just be considered as something done while doing (A), or as being done specifically because (A) is a good opportunity to do it.
This structure may be used either with or without kanji, so it will be important to remember both.
帰(かえ)りがけに駅前(えきまえ)のたこ焼(や)き屋(や)でたこ焼(や)きを買(か)った。
On my way home, I bought some takoyaki from the takoyaki store in front of the station.
今日(きょう)は学校(がっこう)への行(い)きがけにコンビニで弁当(べんとう)を買(か)う。
Today, on my way to school, I will buy lunch at the convenience store.
お父(とう)さん、通(とお)りがけにサービスエリアにでも寄(よ)って行(い)こ!
Dad, let's stop by the service area on the way!
Fun-fact - 掛(か)ける is one of the more difficult verbs in Japanese, as it does not have an exact counterpart in English. However, in most cases it just means to lay, extend, or place something across either a physical or metaphorical surface or span. In this way, it may help to remember (A) as the span from which (B) will occur.