【问题标题】:Angular: Load data from two components to a single component one at a timeAngular:一次将数据从两个组件加载到单个组件
【发布时间】:2020-07-16 16:19:02
【问题描述】:

我正在创建一个新闻门户,我有一个类别组件和一个导航栏组件。这两个组件都包含类别。我的目标是加载特定类别的新闻,如体育、娱乐等。我尝试的是,我的类别组件和导航栏组件都指向同一个新闻组件以加载特定类别的新闻。

问题是我无法这样做,因为当我尝试从导航菜单中选择一个类别时它不起作用,而当我从类别组件中尝试时它有时会起作用,有时不起作用

我想从导航菜单中加载类别,无论它在哪个页面上,也不应该干扰类别组件

分类组件和导航栏组件都指向同一个新闻组件

谁能帮我解决这个问题。

我已经粘贴了我项目中的代码

navbar.component.ts

import { Component, OnInit } from '@angular/core';
import { NavbarService } from '../navbar.service';
import * as $ from "jquery";
import { CategoryService } from '../category.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  dropDownCategories:any

  constructor(public nav: NavbarService, private categories: CategoryService, private router: Router) { 
  }

  //to transfer data to navabr service which goes to the news page
  getTitle(title){
    localStorage.setItem('navCategorySelected',title)
    location.reload()
    this.router.navigate(['/news'])
  }

  ngOnInit(): void {
    //to load categories in drop down list
    this.categories.getCategories().subscribe(res=>{
      this.dropDownCategories=res
      this.dropDownCategories=this.dropDownCategories.result
    })

    //for the drop down animation
    $(document).ready(function () {
      $('.navbar-light .dmenu').hover(function () {
          $(this).find('.sm-menu').first().stop(true, true).slideDown(150);
      }, function () {
          $(this).find('.sm-menu').first().stop(true, true).slideUp(105)
      });
  });

  }  

}

category.component.ts

import { Component, OnInit, HostListener } from '@angular/core';
import { CategoryService } from '../category.service';
import { Router } from '@angular/router';
import { NavbarService } from '../navbar.service';

@Component({
  selector: 'app-category',
  templateUrl: './category.component.html',
  styleUrls: ['./category.component.css']
})
export class CategoryComponent implements OnInit {

  holdCategoryData: any

  isShow: boolean;// for scroll-up
  topPosToStartShowing = 100;//for scroll-up

  constructor(private catergoryService: CategoryService,private router: Router, public nav:NavbarService) {

    this.catergoryService.getCategories().subscribe(catlog => {
      this.holdCategoryData = catlog
      this.holdCategoryData = this.holdCategoryData.result
      console.log('======Category Output is ========', catlog, '====== type of ======', typeof catlog)
    })

  }


  //scroll code begins here
  @HostListener('window:scroll')
  checkScroll() {

    // window의 scroll top
    // Both window.pageYOffset and document.documentElement.scrollTop returns the same result in all the cases. window.pageYOffset is not supported below IE 9.

    const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

    if (scrollPosition >= this.topPosToStartShowing) {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
  }

  // TODO: Cross browsing
  gotoTop() {
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });
  }

  //gets the category name and goes to news page
  getTitle(title) {
    console.log("====Page title is =====", title)
    localStorage.setItem('categorySelected',title)
    this.router.navigateByUrl('/news')
  }
  ngOnInit(): void {
    this.nav.show()//loads navbar

  }

}

news.component.ts

import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';
import { Router } from '@angular/router';
import { NavbarService } from '../navbar.service';

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
  arr=[]

  holdNews:any
  constructor(private allNews:NewsService, private router: Router, public nav:NavbarService) {

    //to get news when category is clicked
    this.allNews.getNews().subscribe(res=>{
      console.log('=========News Component output==========', res)
      this.holdNews=res
      this.holdNews=this.holdNews.result
      this.allNews.holdnews=this.holdNews
    })

    //to get news when navigation elements are clicked
    this.nav.getNews().subscribe(nres=>{
      console.log('=========Nav Component output==========', nres)
      this.holdNews=nres
      this.holdNews=this.holdNews.result
    })
  }

  readMore(title, newsimg,fulldescp){
    localStorage.setItem('det_title',title)
    localStorage.setItem('det_img',newsimg)
    localStorage.setItem('det_fulldescp',fulldescp)
    this.router.navigateByUrl('/detailednews')
  }
  ngOnInit(): void {
    this.nav.show()

  }

}

news.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class NewsService {
  holdnews:any

  constructor(private http:HttpClient) { }

  getNews(){
    let holdHeader=localStorage.getItem('access_token')
    console.log('===Access token is ====',holdHeader)
    let queryParams={start:"0",limit:"10", category:localStorage.getItem('categorySelected')}
    let header = new HttpHeaders({'accesstoken':holdHeader})
    let options = { headers: header }

    return this.http.post<any>('...link...',queryParams,options)
  }

}

navbar.service.ts

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class NavbarService {
  visible: boolean;

  constructor(public http : HttpClient) { this.visible = false; }

  hide() { this.visible = false; }

  show() { this.visible = true; }

  toggle() { this.visible = !this.visible; }

  //to get news when the drop down elements are clicked
  getNews(){
    let holdHeader=localStorage.getItem('access_token')
    console.log('===Access token is ====',holdHeader)
    let queryParams={start:"0",limit:"10", category:localStorage.getItem('navCategorySelected')}
    let header = new HttpHeaders({'accesstoken':holdHeader})
    let options = { headers: header }
    return this.http.post<any>('...link...',queryParams,options)
  }

}

【问题讨论】:

  • 你能分享一下这段代码的 stackblitz URL 吗?
  • @prathameshk73 我在 stackblitz 上没有这个代码,这对这个有点新,所以对角度不太了解
  • 您可以在 github 中提交您的项目并像这样访问它 stackblitz.com/github/{GH_USERNAME}/{REPO_NAME} 请参阅下面的文档stackblitz.com/docs#import-from-github
  • @PratikGhagare 我认为您应该首先阅读有关带父子组件的输入和输出,然后是可观察的(第二个解决方案)。另外我担心的是为什么在这里使用 jquery。您正在使用 jquery 破坏 Angular 的全部目的。

标签: angular angular-services angular-components


【解决方案1】:

我认为你会在 Angular 文档的这一部分找到所有问题的答案:https://angular.io/guide/component-interaction

使用组件父/子关系或服务在组件之间共享信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-02
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多