我使用Angular 7和Laravel 5.8开发应用程序。
Laravel:后端
public function indexSmsmo()
{
if(Auth::user()->id == 1)
$smsmos = Smsmo::all();
else
$smsmos = Smsmo::where('user_id',Auth::user()->id);
return $smsmos;
}
我有用户表和其他表。其他表中有user_id。
auth.service.ts
import { environment } from '../../environments/environment.prod';
import { User } from '../models/user';
@Injectable({
providedIn: 'root'
})
export class AuthService {
public currentUser: User;
private readonly apiUrl = environment.apiUrl;
private environmentService: EnvironmentService;
constructor(
private http: HttpClient,
private router: Router)
{
}
onLogin(user: User): Observable<User> {
const request = JSON.stringify(
{ email: user.email, password: user.password }
);
return this.http.post(this.loginUrl, request, httpOptions)
.pipe(
map((response: User) => {
// Receive jwt token in the response
const token: string = response['access_token'];
// If we have a token, proceed
if (token) {
this.setToken(token);
this.getUser().subscribe();
}
return response;
}),
catchError(error => this.handleError(error))
);
}
此后,我们有登录组件
login.component.ts
ngOnInit() {
document.body.className = 'hold-transition login-page';
$(() => {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' /* optional */
});
});
// Set the return url
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/home';
this.authService.onLogout();
}
onSubmit(loginForm): void {
this.spinnerService.show();
this.authService.onLogin(this.user).subscribe(
(response) => {
this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})
this.router.navigate([this.returnUrl]);
},
(error) => {
this.spinnerService.hide();
this.error = error.error;
}
);
// Clear form fields
loginForm.reset();
}
当我尝试单击菜单以显示终点上其他任何表中的数据时,出现此错误:
然后,当我检查控制台时,我得到了:
但是,如果我从端点删除条件并将控制器设置为:
public function indexSmsmo()
{
$smsmos = Smsmo::all();
return $smsmos;
}
代替最初的:
public function indexSmsmo()
{
if(Auth::user()->id == 1)
$smsmos = Smsmo::all();
else
$smsmos = Smsmo::where('user_id',Auth::user()->id);
return $smsmos;
}
没有错误,但会显示所有内容。我如何实现我的目标。
如果用户登录并且user_id为1,他应该看到所有内容,但如果不是1,则应该看到user_id等于登录ID的数据