Вызов метода на основе URL - PullRequest
0 голосов
/ 09 июня 2019

Я создал data.service.ts, где я создал метод, который имеет информацию о страницах, потому что я не хочу создавать отдельный компонент для каждой страницы, так как он имеет одинаковый макет по всей странице.Теперь я хотел показать эти методы, основанные на URL-адресе, и он работает, но я не думаю, что это правильный способ, которым кто-либо может помочь, пожалуйста.Вот мой код

Я уже создал этот код ниже, который работает в соответствии с ожиданиями, но не знаю, что это исправленный способ, или я могу сократить его до гораздо более простого формата Dataservice



@Injectable({
  providedIn: 'root'
})
export class DataService {

    friend(): Observable<FilterCommon[]>{
    return new Observable<FilterCommon[]>(observer => {
      const refcode: FilterCommon = new FilterCommon();
      refcode.name = 'Sutitle here';
      refcode.heading = 'The title here';
      refcode.action = 'Select this template',
      refcode.link = '/templats/friend',
      refcode.items = [
          {
          content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non tellus eu nulla fringilla fermentum et non ligula. ',
          url: 'assets/images/dashboard-gallery/1.jpg',
          footer: '',
          bottomheading: ''
        }
        ];
      const work: FilterCommon = new FilterCommon();
      work.headingwork = 'How it works';
      work.class = 'bew-ccc';
      work.item = [
               {
                  content: '1',
                  url: 'assets/images/1.png',
                  bottomheading: 'You install the widget',
                  footer: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non tellus eu nulla fringilla fermentum et non ligula. '
                },
                {
                  content: '2',
                  url: 'assets/images/2.png',
                  bottomheading: 'The refer friends',
                  footer: 'Lorem ipsum dolor sit amet.'
                },
                {
                  content: '3',
                  url: 'assets/images/3.png',
                  bottomheading: 'Everyone gets coupon rewards  ',
                  footer: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
                }
          ];

      const friendallpage: FilterCommon[] = [];
      friendallpage.push(refcode);
      friendallpage.push(work);
      observer.next(friendallpage);
      observer.complete();
      });
  }

  Giveaway(): Observable<FilterCommon[]>{
    return new Observable<FilterCommon[]>(observer => {
      const refcode: FilterCommon = new FilterCommon();
      refcode.name = 'Subtitle';
      refcode.heading = 'The Title';
      refcode.action = 'Select this template',
      refcode.link = '/templats/giveaway',
      refcode.items = [
          {
          content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non tellus eu nulla fringilla fermentum et non ligula. ',
          url: 'assets/images/dashboard-gallery/1.jpg',
          footer: '',
          bottomheading: ''
        }
        ];
      const work: FilterCommon = new FilterCommon();
      work.headingwork = 'How it works';
      work.class = 'v-ine';
      work.item = [
               {
                  content: '1',
                  url: 'assets/images/1.png',
                  bottomheading: 'You install the widget',
                  footer: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
                },
                {
                  content: '2',
                  url: 'assets/images/2.png',
                  bottomheading: 'The refer friends',
                  footer: 'this is your moment of glory.'
                },
                {
                  content: '3',
                  url: 'assets/images/3.png',
                  bottomheading: 'Everyone gets coupon rewards  ',
                  footer: ' if you get lost.'
                }
          ];

      const friendallpage: FilterCommon[] = [];
      friendallpage.push(refcode);
      friendallpage.push(work);
      observer.next(friendallpage);
      observer.complete();
      });
  }

  leaderboard(): Observable<FilterCommon[]>{
    return new Observable<FilterCommon[]>(observer => {
      const refcode: FilterCommon = new FilterCommon();
      refcode.name = 'Subtitle here';
      refcode.heading = 'The Title';
      refcode.action = 'Select this template',
      refcode.link = '/templats/leaderboard',
      refcode.items = [
          {
          content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non tellus eu nulla fringilla fermentum et non ligula. ',
          url: 'assets/images/dashboard-gallery/1.jpg',
          footer: '',
          bottomheading: ''
        }
        ];
      const work: FilterCommon = new FilterCommon();
      work.headingwork = 'How it works';
      work.class = 'v-col';
      work.item = [
               {
                  content: '1',
                  url: 'assets/images/1.png',
                  bottomheading: 'You install the widget',
                  footer: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.  '
                },
                {
                  content: '2',
                  url: 'assets/images/2.png',
                  bottomheading: 'The friends',
                  footer: 'this is your moment of glory.'
                },
                {
                  content: '3',
                  url: 'assets/images/3.png',
                  bottomheading: 'Everyone gets',
                  footer: 'tif you get lost.'
                }
          ];

      const friendallpage: FilterCommon[] = [];
      friendallpage.push(refcode);
      friendallpage.push(work);
      observer.next(friendallpage);
      observer.complete();
      });
  }

}


  constructor(private dataService: DataService, private router: Router, private route: ActivatedRoute) {
    this.router.events.subscribe((ev) => {
      if (ev instanceof NavigationEnd) { 
        console.log(ev.url);
        if(ev.url == '/templates/common/referFriend/getd'){
          this.dataService.referfriend().subscribe(data => {
            this.data = data;
          });
        } else if(ev.url == '/templates/modules/Friend'){
          this.dataService.friend().subscribe(data => {
            this.data = data;
          });
        } else if(ev.url == '/templates/modules/ecommercepage'){
          this.dataService.ecommerce().subscribe(data => {
            this.data = data;
          });
        } else if(ev.url == '/templates/modules/leaderboard'){
            this.dataService.leaderboard().subscribe(data => {
              this.data = data;
            });
        } else if(ev.url == '/templates/modules/Giveaway'){
          this.dataService.Giveaway().subscribe(data => {
            this.data = data;
          });
        } else if(ev.url == '/templates/modules/Shopify'){
            this.dataService.shopify().subscribe(data => {
              this.dataRefer = data;
            });
        } else{
            console.log('no url matched');
        }       
      }
    });
  }
  dataRefer: gapshopify[];

  data: friend[];
  ngOnInit() {}
  }

Я получил ожидаемый результат, но мне нужен более правильный путь

Ответы [ 2 ]

0 голосов
/ 09 июня 2019

Я понял, что ваши функции очень похожи в вашей службе данных, и они имеют различия только в нижнем колонтитуле и ссылке, поэтому я закорочил вашу службу данных следующим образом:

@Injectable({
  providedIn: 'root'
 })
 export class DataService {
   friendFooters=[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non tellus 
     eu nulla fringilla fermentum et non ligula. ',
    'Lorem ipsum dolor sit amet.',
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
]
giveawayFooters=[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ',
    'this is your moment of glory.',
    ' if you get lost.'
]
leaderboardFooters=[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit.  ',
    'this is your moment of glory.',
    'tif you get lost.'
]
getData(url): Observable<FilterCommon[]>{
let selectedFooter=[];
let link='';
switch(url){
  case '/templates/modules/Friend':{
    selectedFooter=this.friendFooters;
    link='/templats/friend';
    break
  }
  case '/templates/modules/Giveaway':{
    selectedFooter=this.giveawayFooters;
    link='/templats/giveaway';
    break
  }
  case '/templates/modules/leaderboard':{
    selectedFooter=this.leaderboardFooters;
    link='/templats/leaderboard';
    break
  }
}
return new Observable<FilterCommon[]>(observer => {
  const refcode: FilterCommon = new FilterCommon();
  refcode.name = 'Sutitle here';
  refcode.heading = 'The title here';
  refcode.action = 'Select this template',
    refcode.link = link,
    refcode.items = [
      {
        content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non 
  tellus eu nulla fringilla fermentum et non ligula. ',
        url: 'assets/images/dashboard-gallery/1.jpg',
        footer: '',
        bottomheading: ''
      }
    ];
  const work: FilterCommon = new FilterCommon();
  work.headingwork = 'How it works';
  work.class = 'bew-ccc';
  work.item = [
    {
      content: '1',
      url: 'assets/images/1.png',
      bottomheading: 'You install the widget',
      footer: selectedFooter[0]
    },
    {
      content: '2',
      url: 'assets/images/2.png',
      bottomheading: 'The refer friends',
      footer: selectedFooter[1]
    },
    {
      content: '3',
      url: 'assets/images/3.png',
      bottomheading: 'Everyone gets coupon rewards  ',
      footer: selectedFooter[2]
    }
  ];

  const datapage: FilterCommon[] = [];
  datapage.push(refcode);
  datapage.push(work);
  observer.next(datapage);
  observer.complete();
});
}

}, а также я изменил вашуКод для этого:

  constructor(private dataService: DataService, private router: Router, private 
     route: ActivatedRoute) {
     this.router.events.subscribe((ev) => {
        if (ev instanceof NavigationEnd) {
         console.log(ev.url);
         this.dataService.getData(ev.url).subscribe(data => {
         this.data = data;
      });

   }
 });
 }
  dataRefer: gapshopify[];

  data: friend[];
  ngOnInit() {}
 }

, но это только для 3 функций, которые вы использовали в dataservice, поэтому вы должны завершить дело переключателя самостоятельно.

0 голосов
/ 09 июня 2019

Вы можете просто добавить @Input () в свой компонент и отправить данные для каждой страницы, на которой вы используете этот компонент, как показано ниже:

Ваш файл компонента "ts" должен выглядеть следующим образом:

@Component({
  selector: 'app-main-page',
  templateUrl: './main-page.component.html',
  styleUrls: ['./main-page.component.scss']
})
    export class MainPageComponent {
    @Input() data:any;
    constructor() {
    }
}

и для каждой страницы вам нужен код в файле "ts":

@Component({
  selector: 'app-shopify',
  templateUrl: './shopify.component.html',
  styleUrls: ['./shopify.component.scss']
})
    export class ShopifyComponent {
    dataRefer:any;
    constructor(public dataService : DataService) {
      this.getData();
    }
    getData(){
        this.dataService.shopify().subscribe(data => {
          this.dataRefer = data;
        });
    }
}


@Component({
  selector: 'app-giveaway',
  templateUrl: './giveaway.component.html',
  styleUrls: ['./giveaway.component.scss']
})
    export class GiveawayComponent {
    dataRefer:any;
    constructor(public dataService : DataService) {
      this.getData();
    }
    getData(){
        this.dataService.giveaway().subscribe(data => {
          this.dataRefer = data;
        });
    }
}

и, наконец, угловой тег для каждой страницы должен выглядеть следующим образом:

<app-giveaway [data]="dataRefer"></app-giveaway>

<app-shopify [data]="dataRefer"></app-shopify>
...