在 Angular 4 中单击查看按钮时显示特定详细信息
Display Specific Detail When Click View Button in Angular 4
我需要帮助来完成这项 "view detail function" 工作。首先,我有用户组件,我想模仿它的工作原理。就像您在尝试获取特定内容时必须访问其服务一样。但是用户组件不是来自 api。现在,我想在我的新闻组件中模仿它,详细信息来自 api。我如何访问新闻组件的具体事物细节?我已将下面的代码放在用户组件和新闻 component.Thanks 上以寻求帮助。
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];
}
user-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) {
//
}
news-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]);
}
}
不太明白是什么问题。您正在导航到详细视图 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')
)
}
您将在您的详细信息组件中获得用户 属性 的详细信息,并且您可以根据需要显示它。
更新
要获取新闻的详细信息,您可以创建一个带有行为主题的新闻存储,该行为主题将调用您的服务以获取所有新闻 - 列表。您的组件也可以调用此商店。此商店将公开 getter 您的私人行为主题,将其公开为 Observable。
然后您可以随时通过 getValue() 访问主题值,而不必为任何查看详细信息调用再次调用 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")
);
}
}
我做到了。
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))
}
我需要帮助来完成这项 "view detail function" 工作。首先,我有用户组件,我想模仿它的工作原理。就像您在尝试获取特定内容时必须访问其服务一样。但是用户组件不是来自 api。现在,我想在我的新闻组件中模仿它,详细信息来自 api。我如何访问新闻组件的具体事物细节?我已将下面的代码放在用户组件和新闻 component.Thanks 上以寻求帮助。
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];
}
user-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) {
//
}
news-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]);
}
}
不太明白是什么问题。您正在导航到详细视图 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')
)
}
您将在您的详细信息组件中获得用户 属性 的详细信息,并且您可以根据需要显示它。
更新
要获取新闻的详细信息,您可以创建一个带有行为主题的新闻存储,该行为主题将调用您的服务以获取所有新闻 - 列表。您的组件也可以调用此商店。此商店将公开 getter 您的私人行为主题,将其公开为 Observable。
然后您可以随时通过 getValue() 访问主题值,而不必为任何查看详细信息调用再次调用 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")
);
}
}
我做到了。
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))
}