2017-09-07 70 views
1

我需要幫助使這個「查看細節功能」工作。首先,我有我想模仿它如何工作的用戶組件。就像您在嘗試獲取具體內容時必須訪問其服務一樣。但用戶組件不是來自api。現在,我想在我的新聞組件中模仿它,細節來自api。我如何訪問新聞組件的具體內容?我已將代碼放在用戶組件和新聞組件的下面。感謝您的幫助。當點擊角度4中的查看按鈕時顯示特定細節

user.service.ts

import { User } from './user.model'; 
import { Subject } from 'rxjs/Subject'; 
export class UserService { 

usersChanged = new Subject<User[]>(); 

    private users: User[]= [ 
    new User('Harry', 'James', 99999889), 
    new User('Thomas', 'Baker', 99638798) 
    ]; 

    getUsers() { 
    return this.users.slice(); 
    } 

    getUser(index: number) { 
    return this.users[index]; 
    } 

用戶list.component

import { Component, OnInit } from '@angular/core'; 
import { User } from '../user.model'; 
import { UserService } from '../user.service'; 
import { Router, ActivatedRoute } from '@angular/router'; 

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

    users: User[]; 
    index: number; 

    constructor(private userService: UserService, private router: Router, private route: ActivatedRoute) { } 

    ngOnInit() { 
     this.users = this.userService.getUsers(); 
     this.userService.usersChanged 
     .subscribe(
     (users: User[]) => { 
      this.users = users; 
     } 
    ); 
    } 

    onViewUserDetail(index: number){ 
    this.router.navigate(['users', index]); 
    } 

news.service.ts

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

@Injectable() 
export class NewsService { 
    constructor(private httpClient: HttpClient) { 
    } 

getNews() { 
    const authToken = localStorage.getItem('auth_token'); 
    const headers = new HttpHeaders() 
    .set('Content-Type', 'application/json') 
    .set('Authorization', `Bearer ${authToken}`); 

    return this.httpClient 
     .get('sample/news', { headers: headers }) 
     .map(
     (response => response)); 
} 


getNewsDetail(index: number) { 
    // 
    } 

新聞list.component.ts

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


@Component({ 
    selector: 'app-news-list', 
    templateUrl: './news-list.component.html', 
    styleUrls: ['./news-list.component.css'] 
}) 
export class NewsListComponent implements OnInit { 
    newslists: any; 
    constructor(private newsService: NewsService, private router: Router, private route: ActivatedRoute) { } 

    ngOnInit() { 

    this.newsService.getNews() 
     .subscribe(
     (data:any) => { 
      console.log(data); 
      this.newslists = data.data.data; 
      console.log(this.newslists); 
     }, 
     error => { 
      alert("ERROR"); 
     }); 
    } 

    onViewNewsDetail(id: number){ 
    console.log(id); 
    this.router.navigate(['news', id]); 
    } 

} 

回答

0

我做到了。

getAllNews() { 

    if(this.newslist != null) { 
     return Observable.of(this.newslist); 
    } 

    else { 
     const authToken = localStorage.getItem('auth_token'); 
     const headers = new HttpHeaders() 
     .set('Content-Type', 'application/json') 
     .set('Authorization', `Bearer ${authToken}`); 

     return this.httpClient 
     .get('samplei/news/', { headers: headers }) 
     .map((response => response)) 
     .do(newslist => this.newslist = newslist) 
     .catch(e => { 
      if (e.status === 401) { 
       return Observable.throw('Unauthorized');   
      } 

     }); 
    } 
    } 


    getNews(id: number) { 
    return this.getAllNews().map((data:any)=> data.data.data.find(news => news.id === id)) 
    } 
+0

@JayDeeEss。我做到了?怎麼樣? – Joseph

1

不明白的問題是什麼。您正在瀏覽onView *** Detail()方法的詳細視圖。如果您已經正確定義了您的路線,它應該轉到相應的組件。在該詳細組件ngOnInit()中,您可以訂閱激活路由的paramMap,然後調用api或從商店獲取值,但是您需要。

ngOnInit() { 
     this.paramSubscription = this.route.paramMap 
      .switchMap((params: ParamMap) => this.userService.getUser(+params.get('id'))) 
      .subscribe(
      res => { 
       this.user= <User>res; 
      }, 
      err => console.log('error retreiving user detail') 
      ) 

    } 

你將不得不在用戶屬性的細節在您的詳細成分,還可以顯示它,但是你希望它是。

更新

得到您的新聞內容,您可以創建一個行爲主體,將調用你服務來獲得所有新聞的新聞店 - 這樣的名單。你的組件也可以調用這個商店。該商店將公開您的私人行爲主題的吸氣劑,並將其暴露爲Observable。

然後,您可以通過getValue()在ny時間訪問主題值,並且不必再爲任何視圖細節調用調用api。看下面的例子:

@Injectable() 
    export class NewsStore { 
     private _news: BehaviorSubject<List<News>> = new BehaviorSubject(List([])); 

     constructor(
      private newsService: NewsService) { 
      this.loadInititalData(); 
     } 

     get news() { 
      return this._news.asObservable(); 
     } 

    getNews(id: number): any { 
      return this._news.getValue().filter(news=> news.id == id); 
     } 

loadInititalData() { 
     this.newsService.getAll() 
      .subscribe(
      res => { 
       let news= res; 
       this._news.next(List(news)) 
      }, 
      err => this.handleError(err, "loadinitialdata") 
      ); 
    } 
    } 
+0

我沒有用戶組件的問題。用戶是我想要遵循的示例。用戶沒有api。刷新頁面後,它會消失。我的問題在於新聞組件。它是這樣工作的,如果你點擊新聞,它會顯示新聞列表。在每個新聞列表中,有一個名爲「View」的按鈕,點擊後會顯示該特定新聞的詳細信息。新聞列表是從api – Joseph

+0

所以問題是在viewDetail()在服務? – JayDeeEss

+0

是的。新聞組件的ViewDetail() – Joseph