我需要幫助使這個「查看細節功能」工作。首先,我有我想模仿它如何工作的用戶組件。就像您在嘗試獲取具體內容時必須訪問其服務一樣。但用戶組件不是來自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]);
}
}
@JayDeeEss。我做到了?怎麼樣? – Joseph